/*
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;
}
看截圖:
這時候沒有調用拷貝構造函數。