问题描述
C ++ 11 std :: this_thread :: yield()和 std :: this_thread :: sleep_for()
有什么区别?如何决定何时使用哪个?
What is the difference between C++11 std::this_thread::yield()
and std::this_thread::sleep_for()
? How to decide when to use which one?
推荐答案
std :: this_thread :: yield
告诉实现重新安排线程的执行,在您遇到这种情况时应使用处于繁忙的等待状态,例如在线程池中:
std::this_thread::yield
tells the implementation to reschedule the execution of threads, that should be used in a case where you are in a busy waiting state, like in a thread pool:
...
while(true) {
if(pool.try_get_work()) {
// do work
}
else {
std::this_thread::yield(); // other threads can push work to the queue now
}
}
如果您确实要等待特定时间,可以使用
std :: this_thread :: sleep_for
.这可以用于真正重要的时间任务,例如:如果您真的只想等待2秒.(请注意,实现的等待时间可能会超过给定的持续时间)
std::this_thread::sleep_for
can be used if you really want to wait for a specific amount of time. This can be used for task, where timing really matters, e.g.: if you really only want to wait for 2 seconds. (Note that the implementation might wait longer than the given time duration)
这篇关于std :: this_thread :: yield()与std :: this_thread :: sleep_for()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!