std::this_thread::yield() vs std::this_thread::sleep_for()
std::this_thread::yield() vs std::this_thread::sleep_for()
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)
相关文章:
- 在std::thread中,joinable()然后join()线程安全吗
- 分离一个静态常量 std::thread?
- 当指向对象的指针作为参数传递给 std::thread 时,内存可见性
- 如何从 std::thread 返回值
- 将 std::thread by 值推送到列表中
- 转发变量参数列表以模拟 std::thread
- 对 'std::thread::_M_start_thread CMake 的未定义引用进行基准测试
- std::thread 增加 DLL 引用计数,从而防止卸载 DLL
- 如何防止 std::thread 在 QT 中冻结 GUI?
- 对带有唯一指针的 std::thread 使用类成员函数时出现编译错误
- 为什么参数在构造 std::thread 时移动两次
- std::thread::_Invoker 使用线程编程时出错
- 在线程 A 中创建一个 std::thread 对象,在线程 B 中连接
- 为什么编译器抱怨 std::thread 参数在转换为右值后必须是可调用的?
- ZeroMQ 在使用 std::thread 创建工作线程时崩溃
- 在没有复制构造函数的对象的成员函数中启动 std::thread
- CLang:在 std::thread 中运行函数会导致结构创建BAD_ACCESS
- 调用以CWinThread为基的类运算符()的std::thread失败
- 如何通过std::thread生成多个线程
- std::future::get()或std::future::wait()是std::thread::join()的替