传递类对象-智能指针作为线程参数

/*
1:临时对象作为线程参数:用测试大法
线程id:线程id是一个数字,每一个线程都对应一个线程id,线程不一样,线程id也不一样,用std::this_thread::get_id()来获取。
2:传递类对象,智能指针作为线程参数:在子线程中用const和引用来接
*/
#include <iostream>
#include<thread>
using namespace std;
class A
{
public:
mutable int m_a;//m_a不管在什么情况下都可以修改
A(const int a) :m_a(a) { cout << "Constructor execution! " << " Thread ID:" << this_thread::get_id() << endl; }
A(const A &buffer) :m_a(buffer.m_a) { cout << "Copy constructor execution! " << " Thread ID:" << this_thread::get_id() << endl; }
~A() { cout << "Destructor execution! " << "Thread ID:" << this_thread::get_id() << endl; }
};
void printd(const A &mybuff)//对于类对象,这里一定要用引用来接,而且一定要用const,否则可能会报错,而且这里用拷贝
{
mybuff.m_a = 20;
cout << "Subthreads start executing!" << " Thread ID:" << this_thread::get_id() << endl;
}
int main()
{
A myobj(10);
thread mythread(printd, myobj);//将类对象作为线程参数
mythread.join();//myobj做为类对象传递时,这儿会在主线程中调用拷贝构造函数生成一个临时变量,而不是在子线程中生成一个临时变量。(截图)
//mythread.detach();
//所以不用担心用detach之后,主线程先结束,导致子线程的类对象没有生成的问题。
cout << "The execution of the main thread is over!" << endl;
return 0;
}

看运行结果:

//3:但是如果要修改下面的m_a呢,总不能一直用mutable吧?这时候引入了一个std::ref函数

#include <iostream>
#include<thread>
using namespace std;
class A
{
public:
int m_a;//m_a不管在什么情况下都可以修改
A(const int a) :m_a(a) { cout << "Constructor execution! " << " Thread ID:" << this_thread::get_id() << endl; }
A(const A &buffer) :m_a(buffer.m_a) { cout << "Copy constructor execution! " << " Thread ID:" << this_thread::get_id() << endl; }
~A() { cout << "Destructor execution! " << "Thread ID:" << this_thread::get_id() << endl; }
};
void printd(A &mybuff)//这时候mybuf是myobj的引用,因为ref的作用,也不用const
{
mybuff.m_a = 20;//改变m_a的值
cout << "Subthreads start executing!" << " Thread ID:" << this_thread::get_id() << endl;
}
int main()
{
A myobj(10);
cout << "myobj::m_a:" << myobj.m_a << endl;
thread mythread(printd, ref(myobj));//将类对象作为线程参数
mythread.join();//myobj做为类对象传递时,这儿会在主线程中调用拷贝构造函数生成一个临时变量,而不是在子线程中生成一个临时变量。(截图)
//mythread.detach();
//所以不用担心用detach之后,主线程先结束,导致子线程的类对象没有生成的问题。
cout << "myobj::m_a:" << myobj.m_a << endl;
cout << "The execution of the main thread is over!" << endl;
return 0;
}

看截图:

这时候没有调用拷贝构造函数。

猜你喜欢

转载自www.cnblogs.com/suchang/p/10591261.html