简体   繁体   English

std::this_thread::yield() 对比 std::this_thread::sleep_for()

[英]std::this_thread::yield() vs std::this_thread::sleep_for()

What is the difference between C++11 std::this_thread::yield() and std::this_thread::sleep_for() ? C++11 std::this_thread::yield()std::this_thread::sleep_for()什么std::this_thread::sleep_for() How to decide when to use which one?如何决定何时使用哪一个?

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: 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 can be used if you really want to wait for a specific amount of time.如果您真的想等待特定的时间,则可以使用std::this_thread::sleep_for This can be used for task, where timing really matters, eg: if you really only want to wait for 2 seconds.这可用于时间非常重要的任务,例如:如果您真的只想等待 2 秒。 (Note that the implementation might wait longer than the given time duration) (请注意,实现可能等待比给定的持续时间更长的时间)

std::this_thread::sleep_for() std::this_thread::sleep_for()

will make your thread sleep for a given time (the thread is stopped for a given time).将使您的线程在给定的时间内休眠(线程在给定的时间内停止)。 ( http://en.cppreference.com/w/cpp/thread/sleep_for ) http://en.cppreference.com/w/cpp/thread/sleep_for

std::this_thread::yield() std::this_thread::yield()

will stop the execution of the current thread and give priority to other process/threads (if there are other process/threads waiting in the queue).将停止当前线程的执行并优先执行其他进程/线程(如果队列中还有其他进程/线程在等待)。 The execution of the thread is not stopped.线程的执行不会停止。 (it just release the CPU). (它只是释放CPU)。 ( http://en.cppreference.com/w/cpp/thread/yield ) ( http://en.cppreference.com/w/cpp/thread/yield )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM