std::this_thread::yield() vs std::this_thread::sleep_for()

std::this_thread::yield() vs std::this_thread::sleep_for()

本文关键字:std thread this for sleep yield vs      更新时间:2023-10-16

C++11 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 秒。(请注意,实现可能会等待超过给定的持续时间)

标准::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)