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 @   He_LiangLiang  阅读(39)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2019-11-21 sockaddr和sockaddr_in的区别
2019-11-21 CentOS 6.6 升级GCC G++ (当前最新版本为v6.1.0) (完整)
2019-11-21 telnet: Unable to connect to remote host: Connection refused
2019-11-21 telnet: Unable to connect to remote host: No route to host
2019-11-21 IP地址转换函数
2019-11-21 Linux 网络通信 API详解【转载】
2019-11-21 linux 文件详细信息
点击右上角即可分享
微信分享提示