在编写 Microsoft 特定的 C++ 代码时,有人告诉我,编写Sleep(1)比自旋锁要好得多Sleep(0),因为这样Sleep(0)会占用更多的 CPU 时间,而且,只有在有另一个同等优先级的线程等待运行时才会产生。
但是,对于 C++11 线程库,没有太多关于std::this_thread::yield()vs.效果的文档(至少我能找到) std::this_thread::sleep_for( std::chrono::milliseconds(1) )。第二个肯定更冗长,但是它们对于自旋锁是否同样有效,或者它是否受到影响Sleep(0)vs.的潜在相同陷阱的影响Sleep(1)?
std::this_thread::yield()一个可以接受或std::this_thread::sleep_for( std::chrono::milliseconds(1) )可以接受的示例循环:
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!
}