C++多线程与智能指针

/*
*Definition:
*Author:
*Date:
*/
#include<iostream>
#include<thread>
#include <memory>//智能指针头文件
using namespace std;

class A{
    
    
	mutable int m_i;
public:
	mutable int test_i;//mutable 无论在哪都可以修改 test_i的值
	A(){
    
    }
//g构建一个int类型的类A
	A(int a):m_i(a){
    
    
		cout << "The structor of A: " << this <<". ThreadID is:"<<std::this_thread::get_id()<< endl;
	}
	A(const A &a):m_i(a.m_i){
    
    
		cout << "The copy structor of A: " << this << ". ThreadID is:" << std::this_thread::get_id() << endl;
	}
	virtual ~A(){
    
    
		cout << "The destructor of A: " << this << ". ThreadID is:" << std::this_thread::get_id() << endl;
	}
	//用成员函数指针做线程函数
	void testThread(int num)
	{
    
    
		cout << "TestThread is running " << this << "threadId is:" << this_thread::get_id() << endl;
	}
	//直接调用类作为线程函数
	void operator()(int a)
	{
    
    
		cout << "Class () is running " << this << "threadId is:" << this_thread::get_id() << endl;
	}
};


void printA(const int a,const A &b){
    
    
	//const A
	b.test_i = 1001;//It doesn't effect the parameter in  the main function
	cout << "The A is :" <<&b<< endl;
	cout << "The number a is: " << a << endl;
}

//独占智能指针
void printB(unique_ptr<int>ptr){
    
    
	//接收主线程的空间,就不能用detach,只能用join,防止主线程结束回收空间
}

int main(){
    
    
	int a = 100;
	int b = 1;
	A c(101);
	cout << "ThreadID is:" << std::this_thread::get_id() << endl;
	//thread myobj(printA, b, a);//隐式类型转换,不安全
	//thread myobj(printA, b, A(a));//将int a转化为A类型,防止主线程运行完,销毁main里的a
	//在创建线程的同时,构造临时对象,A(a),传递参数可行。
	//因为A(a)是在主线程中构建的
	/*
	detach总结:
	1.若传递int这类的简单类型参数,建议都是值传递,不要用引用。
	2.如果传递类对象,避免隐式类型转换。应该在创建线程的同时构造出临时对象, A(a)。
	函数的接收参数应该使用引用接收,(const A &b),避免二次拷贝构造临时对象数据。

	*/
	thread myobj(printA, a, ref(c));
	//ref()传递对象c的地址
	//传递main函数里c地址的引用给线程myobj中,修改myobj中的引用就等于修改了main函数中的值
	//省略了拷贝构造函数的过程,增加效率

	//
	unique_ptr<int>mptr(new int(100));//mptr 指向一个100个int空间的内存,内存属于主线程,main结束,系统回收
	//move 将mptr指向的100个int空间让printB函数中的ptr代替指向,而mptr为空。
	std::thread myobj2(printB, move(mptr));

	//
	A threadWork(10);//第一个A类对象
	//15是teatThread的参数,10是threadWork的
	//threadWork直接传递一个拷贝给子线程,可以detach
	thread myobj3(&A::testThread, threadWork, 15);
	//thread myobj3(&A::testThread, ref(threadWork), 15);//直接传递引用
	//thread myobj3(&A::testThread, &threadWork, 15);//等价于ref

	//
	thread myobj4(threadWork, 22);//使用拷贝构造
	//thread myobj4(ref(threadWork), 22);//传递引用,不使用,拷贝构造
	//thread myobj4(&threadWork, 22);//错误


	myobj.detach();
	myobj2.join();
	myobj3.join();//防止主线程提前运行完,销毁threadWork.
	myobj4.join();
	system("PAUSE");
	return 0;

}

猜你喜欢

转载自blog.csdn.net/guanxunmeng8928/article/details/107595312