C++多線程-chap1多線程入門3

這裏,只是記錄自己的學習筆記。

順便和大家分享多線程的基礎知識。然後從入門到實戰。有代碼。

知識點來源:

https://edu.51cto.com/course/26869.html


 

C++11 線程創建的多種方式和參數傳遞

 

 1 #include <iostream>
 2 #include <thread>
 3 #include<string>
 4 using namespace std;
 5 // Linx  -lpthread
 6 
 7 
 8 class Para {
 9 public:
10     Para() { cout << "Create  Para " << endl; }
11     Para(const Para& pa) {
12         cout << "copy Para" << endl;
13     }
14     ~Para() { cout << "Drop  Para" << endl; }
15     string name;
16 };
17 
18 
19 //調用回調函數的時候,會再訪問一次。。。這裏又進行了一次 拷貝構造
20 void ThreadMian(int p1, float p2, string str , Para  pa) {
21     this_thread::sleep_for(1000ms);
22     cout << "ThreadMian p1:" << p1 << ",p2:" << p2 << ",str:" << str <<",pa:"<<pa.name<< endl;
23 }
24 
25 int main(int argc,char* argv[]) {
26 
27     // th 在創建的時候,對所有傳入的參數都做了一次拷貝
28     //float f1 = 12.1f;
29     //thread th(ThreadMian, 103, f1, "test string para");
30     //th.join();
31 
32     thread th;
33     {
34         float f1 = 12.1f;
35         Para pa;  //// 創建對象,會默認構造一個對象。。。
36         pa.name = "test Para classs";
37 
38 
39         //所有的參數做複製
40         th = thread(ThreadMian, 1001, f1, "test para2",pa);//pa傳遞進去之後,thread的構造函數會把參數存一次,這裏會進行一次拷貝構造。
41 
42         //類 Para 析構了3次。是走的拷貝構造函數。。
43     }
44 
45     th.join();
46 
47     return 0;
48 }

 

 

總結:
 th(線程對象) 在創建的時候,對所有傳入的參數都做了一次拷貝

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章