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

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

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

知識點來源:

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


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

特別注意,引用作爲參數傳遞的時候,要加 顯示的 ref 類型標識。

 

 1 //參數傳遞的一些坑
 2 
 3 /********
 4 
 5 1.傳遞空間已經銷燬
 6 2.多線程共享訪問一塊空間
 7 3.傳遞的指針變量的生命週期小於線程
 8 
 9 *********/
10 
11 #include <iostream>
12 #include <thread>
13 #include<string>
14 using namespace std;
15 // Linx  -lpthread
16 
17 
18 class Para {
19 public:
20     Para() { cout << "Create  Para " << endl; }
21     Para(const Para& pa) {
22         cout << "copy Para" << endl;
23     }
24     ~Para() { cout << "Drop  Para" << endl; }
25     string name;
26 };
27 
28 
29 //調用回調函數的時候,會再訪問一次。。。這裏又進行了一次 拷貝構造
30 void ThreadMian(int p1, float p2, string str, Para  pa) {
31     this_thread::sleep_for(1000ms);
32     cout << "ThreadMian p1:" << p1 << ",p2:" << p2 << ",str:" << str << ",pa:" << pa.name << endl;
33 }
34 
35 
36 void ThreadMainPtr(Para* pt) {
37     this_thread::sleep_for(100ms);
38     cout << "ThreadMainPtr " << pt->name << endl;
39 }
40 
41 void ThreadMainRef(Para& refP) {
42     this_thread::sleep_for(100ms);
43     cout << "ThreadMainRef " << refP.name << endl;
44 }
45 
46 
47 
48 int main(int argc, char* argv[]) {
49     //{
50     //    //傳遞線程 指針
51     //    Para p;
52     //    p.name = "test ThreadMainPtr name";
53     //    thread th(ThreadMainPtr, &p);//錯誤,線程訪問的P空間會提前釋放
54     //    //解決方案:提高p的生命週期。確保對象p的生命週期和線程的生命週期是一致的。
55     //    //或者把對象p放到堆裏面(提高了它的生命週期)。或者給對象p加鎖。。。
56 
57     //    th.detach();
58     //    //th.join();
59     //}
60     //getchar();
61 
62     {
63         //傳遞線程 引用
64         Para  p;
65         p.name = "test ref";
66 
67         //thread的構造函數是一個模板函數,模板函數找到一個引用之後,不知道是引用,以爲是個普通參數,
68         //然後去找這個相應的函數名,結果找不到。。。對引用,要加 顯示的 ref 類型標識一下,這個參數是一個引用。
69         thread th(ThreadMainRef, ref(p));
70         th.join();
71     }
72 
73 
74 
75     return 0;
76 }

 

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