pol*_*pts 40 c++ multithreading c++11
我想知道C++ 11 std::this_thread::yield()和C++之间有什么区别std::this_thread::sleep_for()?以及如何决定使用什么?谢谢.
inf*_*inf 33
std::this_thread::yield 告诉实现重新安排线程的执行,这应该在你处于忙等待状态的情况下使用,比如在线程池中:
...
while(true) {
if(pool.try_get_work()) {
// do work
}
else {
std::this_thread::yield(); // other threads can push work to the queue now
}
}
Run Code Online (Sandbox Code Playgroud)
std::this_thread::sleep_for如果你真的想等待一段特定的时间,可以使用它.这可以用于任务,时间非常重要,例如:如果你真的只想等待2秒钟.(请注意,实现可能会等待超过给定的持续时间)
nea*_*eam 16
的std :: this_thread :: sleep_for()
将使您的线程在给定时间内休眠(线程在给定时间内停止).(http://en.cppreference.com/w/cpp/thread/sleep_for)
的std :: this_thread ::收率()
将停止当前线程的执行并优先考虑其他进程/线程(如果队列中有其他进程/线程等待).线程的执行没有停止.(它只是释放CPU).(http://en.cppreference.com/w/cpp/thread/yield)