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;
}
本文介绍使用C++进行多线程编程的四种常见方法:通过函数指针、函数对象、lambda表达式及成员函数创建线程。每种方法都提供了具体的代码示例,并解释了其实现细节。
1164

被折叠的 条评论
为什么被折叠?



