title: Correct way to wait on a std::atomic<int> in Windows?
body: <p>The following code works however it has a problem:</p>
  
  <pre><code>#include &lt;atomic&gt;
  #include "windows.h"
  
  std::atomic&lt;int&gt; foo;
  
  DWORD WINAPI baz(void *) { Sleep(10000); foo.store(1); return 0;}
  
  int main()
  {
      foo.store(0);
      HANDLE h = CreateThread(NULL, 0, baz, NULL, 0, NULL);
  
      while ( !foo.load() )
      {
          Sleep(0);
      }
      WaitForSingleObject(h, INFINITE);
      CloseHandle(h);
      return 0;
  }
  </code></pre>
  
  <p>The program uses maximum CPU while it is waiting.  </p>
  
  <p>If I change <code>Sleep(0);</code> to <code>Sleep(1);</code> then it uses 0% CPU, however I am worried about a couple of things:</p>
  
  <ul>
  <li>This introduces an unnecessary delay into my program: it will waste some microseconds if the flag is set in between polls</li>
  <li>This might still be consuming more system resource than is necessary, in order to wake up and call <code>load()</code> every millisecond.</li>
  </ul>
  
  <p>Is there a better way? </p>
  
  <p><em>Background:</em> I have some code that is working using Win32 Events to wake the thread up , using <code>WaitForMultipleObjects</code>, but I'm wondering if I can use <code>std::atomic</code> flags instead, with the aim of perhaps making the code simpler, faster, and/or more portable. IDK how the OS implements WaitForSingleObject and WaitForMultipleObjects, e.g. whether it is using <code>Sleep(1)</code> on those internally too or if it has some smarter technique available.</p>
  
  <p><em>Note:</em> The <code>atomic&lt;int&gt;</code> is lock-free; the generated assembly for the loop is:</p>
  
  <pre><code>    movq    __imp_Sleep(%rip), %rbx
      movq    %rax, %rsi
      jmp .L4
      .p2align 4,,10
  .L5:
      xorl    %ecx, %ecx
      call    *%rbx
  .L4:
      movl    foo(%rip), %edx
      testl   %edx, %edx
      je  .L5
  </code></pre>