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

C++11启动线程的多种方式

2017-10-02 15:16 337 查看
1、通过函数指针创建线程

#include<iostream>
#include<thread>

using namespace std;

void counter(int id,int numIterations)
{
for(int i=0;i<numIterations;++i)
{
cout<<"Counter "<<id<<" has value "<<i<<endl;
}
}
int main()
{
cout.sync_with_stdio(true);
thread t1(counter,1,6);
thread t2(counter,2,4);
t1.join();
t2.join();
return 0;
}
2、通过函数对象创建线程

#include<iostream>
#include<thread>

using namespace std;
class Counter
{
public:
Counter(int id,int numIterations):mId(id),mNumIterations(numIterations)
{
}
void operator()() const
{
for(int i=0;i<mNumIterations;++i)
{
cout<<"Counter "<<mId<<" has value "<<i<<endl;
}
}
protected:
int mId;
int mNumIterations;
};

int main()
{
cout.sync_with_stdio(true);
thread t1{Counter(1,20)};//1.C++11统一初始化语句

Counter c(2,12);//2.定义一个实例,然后传递给thread类的构造函数
thread t2(c);

thread t3(Counter(3,10));//3.使用的圆括号
t1.join();
t2.join();
t3.join();
return 0;
}
3、通过lambda创建线程

#include<iostream>
#include<thread>

using namespace std;

int main()
{
cout.sync_with_stdio(true);

thread t1([](int id,int numIterations)
{
for(int i=0;i<numIterations;++i)
{
cout<<"Counter "<<id<<" has value "<<i<<endl;
}
},1,5);
t1.join();
return 0;
}


4、通过成员函数创建线程

#include<iostream>
#include<thread>

using namespace std;

class Request
{
public:
Request(int id):mId(id){}
void process()
{
cout<<"Processing request "<<mId<<endl;
}
protected:
int mId;
};

int main()
{
cout.sync_with_stdio(true);
Request req(100);
thread t{&Request::process,&req};
t.join();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: