I was told when writing Microsoft specific C++ code that writing Sleep(1)
is much better than Sleep(0)
for spinlocking, due to the fact that Sleep(0)
will use more of the CPU time, moreover, it only yields if there is another equal-priority thread waiting to run.
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 std::this_thread::yield()
vs. std::this_thread::sleep_for( std::chrono::milliseconds(1) )
; 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 Sleep(0)
vs. Sleep(1)
?
An example loop where either std::this_thread::yield()
or std::this_thread::sleep_for( std::chrono::milliseconds(1) )
would be acceptable:
void SpinLock( const bool& 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!
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…