title: Reading interlocked variables
body: <p>Assume:</p>
  
  <p>A. C++ under WIN32.</p>
  
  <p>B. A properly aligned volatile integer incremented and decremented using <code>InterlockedIncrement()</code> and <code>InterlockedDecrement()</code>.</p>
  
  <pre><code>__declspec (align(8)) volatile LONG _ServerState = 0;
  </code></pre>
  
  <p>If I want to simply read _ServerState, do I need to read the variable via an <code>InterlockedXXX</code> function?</p>
  
  <p>For instance, I have seen code such as:</p>
  
  <pre><code>LONG x = InterlockedExchange(&amp;_ServerState, _ServerState);
  </code></pre>
  
  <p>and</p>
  
  <pre><code>LONG x = InterlockedCompareExchange(&amp;_ServerState, _ServerState, _ServerState);
  </code></pre>
  
  <p>The goal is to simply read the current value of <code>_ServerState</code>.</p>
  
  <p>Can't I simply say:</p>
  
  <pre><code>if (_ServerState == some value)
  {
  // blah blah blah
  }
  </code></pre>
  
  <p>There seems to be some confusion WRT this subject. I understand register-sized reads are atomic in Windows, so I would assume the <code>InterlockedXXX</code> function is unnecessary.</p>
  
  <p>Matt J.</p>
  
  <hr>
  
  <p>Okay, thanks for the responses. BTW, this is Visual C++ 2005 and 2008.</p>
  
  <p>If it's true I should use an <code>InterlockedXXX</code> function to read the value of <code>_ServerState</code>, even if just for the sake of clarity, what's the best way to go about that?</p>
  
  <pre><code>LONG x = InterlockedExchange(&amp;_ServerState, _ServerState);
  </code></pre>
  
  <p>This has the side effect of modifying the value, when all I really want to do is read it. Not only that, but there is a possibility that I could reset the flag to the wrong value if there is a context switch as the value of <code>_ServerState</code> is pushed on the stack in preparation of calling <code>InterlockedExchange()</code>.</p>
  
  <pre><code>LONG x = InterlockedCompareExchange(&amp;_ServerState, _ServerState, _ServerState);
  </code></pre>
  
  <p>I took this from an example I saw on MSDN.<br>
  See <a href="http://msdn.microsoft.com/en-us/library/ms686355&#40;VS.85&#41;.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms686355&#40;VS.85&#41;.aspx</a></p>
  
  <p>All I need is something along the lines:</p>
  
  <pre><code>lock mov eax, [_ServerState]
  </code></pre>
  
  <p>In any case, the point, which I thought was clear, is to provide thread-safe access to a flag without incurring the overhead of a critical section. I have seen LONGs used this way via the <code>InterlockedXXX()</code> family of functions, hence my question.</p>
  
  <p>Okay, we are thinking a good solution to this problem of reading the current value is:</p>
  
  <pre><code>LONG Cur = InterlockedCompareExchange(&amp;_ServerState, 0, 0);
  </code></pre>