title: C++11 Thread waiting behaviour: std::this_thread::yield() vs. std::this_thread::sleep_for( std::chrono::milliseconds(1) )
body: <p>I was told when writing Microsoft specific C++ code that writing <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms686298%28v=vs.85%29.aspx" rel="noreferrer"><code>Sleep(1)</code></a> is much better than <code>Sleep(0)</code> for spinlocking, due to the fact that <code>Sleep(0)</code> will use more of the CPU time, moreover, it only yields if there is another <em>equal-priority</em> thread waiting to run.</p>
  
  <p>However, with the C++11 thread library, there isn't much documentation (at least that I've been able to find) about the effects of <code>std::this_thread::yield()</code> vs. <code>std::this_thread::sleep_for( std::chrono::milliseconds(1) )</code>; the second is certainly more verbose, but are they both equally efficient for a spinlock, or does it suffer from potentially the same gotchas that affected <code>Sleep(0)</code> vs. <code>Sleep(1)</code>?</p>
  
  <p>An example loop where either <code>std::this_thread::yield()</code> or <code>std::this_thread::sleep_for( std::chrono::milliseconds(1) )</code> would be acceptable:</p>
  
  <pre><code>void SpinLock( const bool&amp; bSomeCondition )
  {
      // Wait for some condition to be satisfied
      while( !bSomeCondition )
      {
           /*Either std::this_thread::yield() or 
             std::this_thread::sleep_for( std::chrono::milliseconds(1) ) 
             is acceptable here.*/
      }
  
      // Do something!
  }
  </code></pre>