当前位置:   article > 正文

C++中关于this_thread的全局函数_this_tread

this_tread

在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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

以下是执行结果:

4
thread ID: 18800
thread sleep three seconds
thread sleep three seconds again

  • 1
  • 2
  • 3
  • 4
  • 5

参考《C++标准库》

谢谢阅读

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/489793
推荐阅读
相关标签
  

闽ICP备14008679号