C++多线程-chap1多线程入门2
这里,只是记录自己的学习笔记。
顺便和大家分享多线程的基础知识。然后从入门到实战。有代码。
知识点来源:
https://edu.51cto.com/course/26869.html
std::thread 对象生命周期、线程等待和分离
1 #include <iostream> 2 #include <thread> 3 using namespace std; 4 bool is_exit = false; 5 6 void ThreadMainB() { 7 8 cout << "begin ThreadMainB id:" << this_thread::get_id() << endl; 9 10 //睡眠10秒 11 for (int i = 0; i < 5; i++) { 12 if (!is_exit) break; 13 cout << " in thread " << i << endl; 14 this_thread::sleep_for(chrono::seconds(1));//1000ms 15 this_thread::sleep_for(1000ms);//1000ms 16 } 17 18 cout << "end ThreadMainB id:" << this_thread::get_id() << endl; 19 } 20 21 22 int main(int argc, char* argv[]) 23 { 24 { 25 //错误示例:thread对象被销毁,但是它的线程还在运行 26 // thread th(ThreadMain); 27 } 28 29 { 30 //thread th(ThreadMainB); 31 //th.detach();//子线程与主线程分离 守护进程 32 ////坑:主线程退出后,子线程不一定退出。。。 33 //// 主线程退出,相应的资源都释放了。。子线程还未退出,如果访问了这些被释放的资源,会出错。。。 34 } 35 36 { 37 //正确示例 38 //thread th(ThreadMainB); 39 //th.join();//主线程阻塞,等待子线程退出 40 } 41 42 { 43 //线程分离 44 thread th(ThreadMainB); 45 this_thread::sleep_for(chrono::seconds(4)); 46 47 is_exit = true;//通知子线程退出 48 cout << "主线程阻塞,等待子线程退出" << endl; 49 50 th.join();//主线程阻塞,等待子线程退出 51 cout << "子线程已经退出!" << endl; 52 } 53 54 55 56 57 getchar(); 58 return 0; 59 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 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 文件详细信息