C++温故补缺(十六):this_thread类
this_thread类
this_thread是一个类,有4个功能函数:
get_id()
获取当前线程id
#include<iostream>
#include<thread>
using namespace std;
void fun(){
cout<<"hello"<<endl;
}
int main(){
thread th1(fun);
cout<<th1.get_id()<<endl;
th1.join();
}
yield
放弃当前线程占用的时间片,使CPU重新调度以便其他线程执行。
为了展示yield的效果,把程序绑定到一个cpu上处理。使用以下代码,把cpp程序绑定在指定的cpu上:
int your_fixed_cpu_kernl=3;
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
CPU_SET(your_fixed_cpu_kernl,&cpuset);
int rc =pthread_setaffinity_np(pthread_self(),sizeof(cpu_set_t), &cpuset);
if (rc != 0) {
std::cerr << "Error calling pthread_setaffinity_np: " << rc << "\n";
}
并且在编译时需要链接pthread库
代码:
本来该并行执行的多线程任务,被指定到单个CPU上并发执行,当运行到yield暂停当前线程,执行其他线程,之后再返回继续执行。
编译:
g++ test.cpp -o test -lpthread
结果:
sleep_for和sleep_until
都是延时线程的函数
sleep_for()要和std::chrono::seconds,minutes,hours连用,设定暂停的时间。
sleep_until和chrono::system_clock连用,设定暂停到一个时间点。
本文来自博客园,作者:Tenerome,转载请注明原文链接:https://www.cnblogs.com/Tenerome/p/cppreview16.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)