C++创建线程


#include <iostream>
#include <thread>
#include <list>

using namespace std;

class Seeking
{
public: 
	void makeFriend()
	{
		for(int i=0; i<10000; i++)
		{
			mm.push_back(i);
		}
	}

	void breakUp()
	{
		for(int i=0; i<10000; i++)
		{
			mm.pop_front();
		}

	}
protected:
	list<int> mm;
}
class MM
{
public:
	void operater()
	{
		count << "子线程启动。。。。。“ << endl;
	}

	void print(int &num)
	{
		num = 1001;
		count << "子线程启动。。。。。“ << this_thread::get_id() <<  endl;
	}
}

void printInfo(int &num)
{
	count << "子线程启动。。。。。“ << endl;
}

void print(unique_ptr<int> ptr)
{
	count <<   ptr.grt() << endl ;
}

void print()
{
	count << "子线程”<< endl ; 
}
int main()
{
	//普通函数创建线程
	thread test0(print);
	//test0.join();
	test0.detach(); //只能join或detach; join阻塞主线程,detach从主线程中分离,创建线程后必须处理

	//通过类对象创建线程
	MM mm;
	thread test1(mm);
	if(test1.joinable)
	{
		test1.join();   //阻塞主线程
	}
                thread test2((MM()));  //需加括号
 	test2.detach(); //从主线线程中分类

	//通过Lambada表达式创建线程
	int (*pMax)(int, int) = nullptr;  
	pMax = [](int a, int b) {return a>b? a : b;}; //捕获参数,函数参数,是捕获异常
	count pMax(1, 2);
	[](){}(count << "Hellow Word!";);

	thread test3([](){count << "子线程启动..”<< endl; });
	test3.join();

	//带参数的线程处理函数的创建
	int num = 0;
	//std::ref 用于包装传递引用值
	thread test4(printInfo, std::ref(num));
	
	//以智能指针为参数的函数充当线程函数
	int *p = new int(1000);
                count  << *p << endl ;
	unique_ptr<int> ptr(new int(1000));
	thread test5(print, move(ptr));//move以后,主线就没有了	
	test5.join();
	count  <<  this_thread::get_id() << endl;

	//以类的成员函数充当线程
	MM mm;
	int num = 1007;
	thread test6(&MM::print, mm, ref(num));
	test6.join();
	
	//多线程访问数据
	Seaking fx;
	thread test7(&Seaking::makeFriend, fx);
	thread test8(&Seaking::breakUp, fx);
	//数据共享,需要加锁
	thread test7(&Seaking::makeFriend, &fx);
	thread test8(&Seaking::breakUp, &fx);

	return 0;
}
上一篇:C++多线程join,detach


下一篇:linux中pthread_join()与pthread_detach()详解