Fork me on Github Fork me on Gitee

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连用,设定暂停到一个时间点。

posted @   Tenerome  阅读(35)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
点击右上角即可分享
微信分享提示