title: Should InterlockedExchange be used on all setting of a variable?
body: <p>I'm using InterlockedExchange  in Windows and I have two questions that put together are basically my title question.</p>
  <p>InterlockedExchange uses type LONG (32-bits). According to Microsoft's documentation <a href="https://docs.microsoft.com/en-us/windows/win32/sync/interlocked-variable-access" rel="nofollow noreferrer">Interlocked Variable Access</a>: <em>&quot;simple reads and writes to 32-bit variables are atomic operations without InterlockedExchange&quot;</em>. According to function documentation <a href="https://docs.microsoft.com/en-us/windows/win32/api/winnt/nf-winnt-interlockedexchange" rel="nofollow noreferrer">InterlockedExchange</a>: <em>&quot;This function is atomic with respect to calls to other interlocked functions&quot;</em>. <strong>Is it or is it not atomic to read/write a LONG in Windows without the interlocked functions?</strong></p>
  <p>I am reviewing some code in which one thread sets a variable then all further accesses on that variable by that thread or any number of threads it created use InterlockedExchange.  To make it simple consider thread running <code>main()</code> creates a thread running <code>other()</code>:</p>
  <pre class="lang-c prettyprint-override"><code>LONG foo;
  
  main()
  {
    foo = TRUE;
    createthread(other());
    /* do other things */
    if(InterlockedExchange(&amp;foo, 0))
    {
       cleanup()
    }
  }
  
  other()
  {
    /* do other things */
    if(InterlockedExchange(&amp;foo, 0))
    {
       cleanup()
    }
  }
  
  cleanup()
  {
  /* it's expected this is only called once */
  }
  </code></pre>
  <p><strong>Is it possible in this example that <code>foo</code> will not appear TRUE to either of the InterlockedExchange calls?</strong> If main is busy doing other things so that the first InterlockedExchange call is made from the other thread, does that mean foo is guaranteed to have been written by the main thread and visible to the other thread at that time?</p>
  <p>Sorry if this is unclear I don't know how to phrase it better.</p>