您的位置:首页 > 编程语言 > C语言/C++

c++11 thread 封装线程类

2016-01-21 11:01 609 查看
c++ thread也挺好用的,也可以像qt thread那样,start启动,run函数为线程的实际运行代码。thread和this_thread方法不多,常用的就几个。

1.std::this_thread::get_id 获取线程id

2.yield,和sleep。yield,交出cpu占有权,一般可以放到多线程的循环里,减少cpu空转

3.一般代码构建完thread,线程跑起来detach一下,qt是默认会detach的。join实际代码一般不用,就主线程等待其他多个线程结束会用到下。

#include <thread>

class TestThread
{
public:
void start(){
thread t(std::bind(&TestThread::run,this));
t.detach();
}

void run(){
while (true){
cout << "test thread id:" << std::this_thread::get_id()<<endl;
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
}
}
};

void run(){
while (true){
cout << "function thread id:" << std::this_thread::get_id() << endl;
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
}
}

int main(void)
{
cout << "main thread id:" << std::this_thread::get_id() << endl;

TestThread testThread;
testThread.start();
thread funcThread(&run);
funcThread.detach();

getchar();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: