C/C++教程

C++多线程2

本文主要是介绍C++多线程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 }

 

这篇关于C++多线程2的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!