我們知道,線程的創建方式有三種:通過函數入口創建,通過類對象創建,通過lambda表達式創建。
在創建線程的同時,可以同時傳遞多個參數,傳參方式有以下幾種:
1.傳入函數參數
1 //1.傳遞函數參數 2 void print1(int i,const char *ptr){ 3 cout << "參數是通過Thread對象傳遞進來的" <<i<<*ptr<< endl; 4 } 5 6 7 8 int main() 9 { 10 //Father *fa = new Child1(); 11 //delete fa; 12 ////Child1 ch; 13 int num = 10; 14 char arr[10] = { 'a','b' }; 15 thread mytobj(print1, num, arr); 16 mytobj.join(); 17 cout << "主線程執行完了" << endl; 18 }
可以看到,使用join()函數,讓主線程等待子線程執行完畢,主線程再輸出。join的好處是使程序受我們自己控制。輸出是:
2.傳入類對象
1 class ArgThread { 2 private: 3 int m_num; 4 public: 5 //構造函數 6 ArgThread(int num) :m_num(num) { 7 cout << "創建線程的同時傳入類的私有成員變量" << this << " " << num << endl; 8 } 9 //拷貝構造函數 10 ArgThread(const ArgThread &AT) { 11 cout << "拷貝構造函數執行" << this << " " << endl; 12 } 13 //拷貝賦值函數 14 ArgThread* operator=(const ArgThread &AT) { 15 this->m_num = AT.m_num; 16 return this; 17 } 18 //為多線程對象重載運算符() 19 void operator()(int p_num,string str) { 20 cout << "線程的入口函數" << this << " " << p_num << str.c_str()<<endl; 21 } 22 void print3() { 23 cout << "通過線程中的對象調用的成員函數" << endl; 24 } 25 }; 26 27 void print2(int i, ArgThread &at) { 28 at.print3(); 29 cout << "參數是通過Thread對象傳遞進來的" << i << &at << endl; 30 } 31 32 int main() 33 { 34 //Father *fa = new Child1(); 35 //delete fa; 36 ////Child1 ch; 37 int num = 10; 38 char arr[] = "good boy!!!!"; 39 /*thread mytobj(print1, num, arr); 40 mytobj.join();*/ 41 ArgThread AT(num); 42 thread mytobj(print2,num,std::ref(AT)); 43 mytobj.join(); 44 cout << "主線程執行完了" << endl; 45 }
輸出:
可以看到,我們創建線程的同時傳入了一個類的對象,使用引用來接收對象,故而不存在問題。