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 }

 

posted @ 2021-11-21 13:45  He_LiangLiang  阅读(39)  评论(0编辑  收藏  举报