有人告诉我,当编写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)主场迎战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!
}
Run Code Online (Sandbox Code Playgroud) 以下语句是否等同于放弃当前线程的时间片?
std::this_thread::sleep_for(std::chrono::milliseconds(0));
std::this_thread::yield;
Sleep(0); // On windows
Run Code Online (Sandbox Code Playgroud)