相关疑难解决方法(0)

C++ 11线程等待行为:std :: this_thread :: yield()与std :: this_thread :: sleep_for(std :: chrono :: milliseconds(1))

有人告诉我,当编写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)

c++ multithreading standard-library c++11

34
推荐指数
3
解决办法
2万
查看次数

放弃C++中当前线程的时间片

以下语句是否等同于放弃当前线程的时间片?

std::this_thread::sleep_for(std::chrono::milliseconds(0));
std::this_thread::yield;
Sleep(0);  // On windows
Run Code Online (Sandbox Code Playgroud)

c++ multithreading c++11

6
推荐指数
2
解决办法
3969
查看次数

标签 统计

c++ ×2

c++11 ×2

multithreading ×2

standard-library ×1