赞
踩
在C++中,标准库提供了一个针对任何线程(包括主线程)的一个命名空间std::this_thread,声明于头文件this_thread中,其中提供了线程专属的一些全局函数。
包括:
操作 | 效果 |
---|---|
this_thread::get_id() | 获取当前线程的ID |
this_thread::sleep_for(dur) | 将某个线程阻塞(block)dur时间段 |
this_thread::sleep_until(tp) | 将某个线程阻塞(block)直到时间点tp |
this_thread::yield() | 建议释放控制以便重新调度,让下一个线程能够执行 |
上表中,第一个接口用于获取当前线程的ID,唯一标识此线程。
第二、三个接口用于使当前线程休眠。
第四个接口this_thread::yield()用于告诉操作系统,放弃当前线程的时间片余额是有好处的,这将使运行环境得以重新调度,以便允许其他线程执行。
通常,当等待或轮询另一线程,或等待或轮询某个flag被另一个线程设定时,可以进行yield()操作。另外,当尝试锁定多个lock/mutex却无法获取其中一个lock或mutex,那么在尝试不同次序的lock/mutex之前可以使用yield(),会让程序更快一点。
以下是代码示例:
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <thread> #include <chrono> using namespace std; int main() { // 获取当前系统并行线程的参考数量 cout << thread::hardware_concurrency() << endl; // 获取当前线程的ID cout << "thread ID: " << this_thread::get_id() << endl; // 当前线程休眠3秒 cout << "thread sleep three seconds" << endl; chrono::duration<int, ratio<1>> d(3); // 3秒,ratio<1>代表时间单位为1秒 this_thread::sleep_for(d); // this_thread::sleep_for(chrono::milliseconds(3000)); // 当前线程休眠至3秒后 cout << "thread sleep three seconds again" << endl; chrono::time_point<chrono::system_clock> time = chrono::system_clock::now() + chrono::seconds(3); this_thread::sleep_until(time); // 当前线程让出时间片 this_thread::yield(); return 0; }
以下是执行结果:
4
thread ID: 18800
thread sleep three seconds
thread sleep three seconds again
参考《C++标准库》
谢谢阅读
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。