C++11中
std::this_thread::yield()
和std::this_thread::sleep_for()
有什么区别?如何决定使用哪一个?std::this_thread::yield()
和std::this_thread::sleep_for()
有什么区别?如何决定使用哪一个?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
}
}
std::this_thread::sleep_for
可以用于在特定的时间内等待,这可以用于那些时间非常关键的任务中,例如:如果你只想等待2秒钟。请注意,该实现可能会比给定的时间长。
std::this_thread::yield
只是让调度程序去执行另一个线程。当调度程序回到这个线程时,它会在调用 std::this_thread::yield
后继续工作。 - Stephan Dollbergstd::this_thread::sleep_for()
该函数可以使当前线程休眠一段给定的时间(停止执行一段时间)。 (http://en.cppreference.com/w/cpp/thread/sleep_for)
std::this_thread::yield()
该函数会停止当前线程的执行,并优先考虑其他进程/线程(如果有其他进程/线程等待在队列中)。 该线程的执行不会被停止(只是释放了CPU)。 (http://en.cppreference.com/w/cpp/thread/yield)
yield
不会抛出异常。sleep_for
可能会抛出异常。 - dirkgentlysleep_for
也不会抛出异常,如果 chrono::duration 类型不抛出异常的话,这对于标准类型来说是正确的,详见30.3.2.9。 - Stephan Dollberg