1. 程式人生 > >C++11啟動執行緒的多種方式

C++11啟動執行緒的多種方式

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