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

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

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; 
}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值