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库

代码:

#include<iostream>
#include<thread>
using namespace std;

void fun(){
    cout<<"th1"<<endl;
    this_thread::yield();
    cout<<"th1.1"<<endl;
}

void fun1(){
    cout<<"th2"<<endl;
    this_thread::yield();
    cout<<"th2.1"<<endl;
}
int main(){
    //绑定到0号CPU
    int cpu_kernl=0;
    cpu_set_t cpuset;
    CPU_ZERO(&cpuset);
    CPU_SET(cpu_kernl,&cpuset);
    int rc=pthread_setaffinity_np(pthread_self(),sizeof(cpu_set_t),&cpuset);
    if(rc!=0){
        cerr<<"Error calling pthread_setaffinity_np"<<rc<<endl;
    }
    //end
    thread th1(fun);
    thread th2(fun1);
    th1.join();
    th2.join();
}

本来该并行执行的多线程任务,被指定到单个CPU上并发执行,当运行到yield暂停当前线程,执行其他线程,之后再返回继续执行。

编译:

g++ test.cpp -o test -lpthread

结果:

sleep_for和sleep_until

都是延时线程的函数

sleep_for()要和std::chrono::seconds,minutes,hours连用,设定暂停的时间。

sleep_until和chrono::system_clock连用,设定暂停到一个时间点。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值