C++多线程-chap2多线程通信和同步8-条件变量

这里,只是记录自己的学习笔记。

顺便和大家分享多线程的基础知识。然后从入门到实战。有代码。

知识点来源:

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


 

 

 

 

 

这里,最关键是要理解 cv.wait 在第2个参数是lambda表达式的时候,是如何处理的。

 

 1 #include <iostream>
 2 #include <thread>
 3 #include <mutex>
 4 #include <string>
 5 #include <list>
 6 #include <sstream>
 7 using namespace std;
 8 
 9 list<string> msgs_;
10 mutex mux;
11 condition_variable cv;
12 
13 void ThreadWrite() {
14     for (int i=0;;++i)
15     {
16         stringstream ss;
17         ss << "Write msg "<< i;
18         unique_lock<mutex> lock(mux);
19         msgs_.push_back(ss.str());
20         lock.unlock();
21         
22         //cv.notify_one(); //发送信号
23         cv.notify_all(); //发送信号
24 
25         this_thread::sleep_for(2000ms);
26     }
27 }
28 
29 void ThreadRead(int i) {
30     for (;;) {
31         cout << "read msg" << endl;
32         unique_lock<mutex> lock(mux);
33         //cv.wait(lock);//解锁, 阻塞 等待信号
34 
35         //lambda表达式
36         cv.wait(lock, [i] {
37             cout <<i<< " wait --msgSize:" << msgs_.size()<< endl;
38 
39             //返回true,不会阻塞,代码继续往下执行
40             // return true;
41 
42             //返回false,会阻塞,直到有通知到来,才会再次进入lambda函数再次判断
43             //return false;
44 
45             //记住一点,返回true 不会阻塞。。。
46             return !msgs_.empty();
47         });
48 
49         //获取信号后锁定
50         while (!msgs_.empty()) {
51             cout << i << " read "<< msgs_.front() << endl;
52             msgs_.pop_front();
53         }
54     }
55 }
56 
57 int main() {
58 
59     thread th(ThreadWrite);
60     th.detach();
61 
62     for (int i = 0; i < 3; i++) {
63         thread th(ThreadRead, i + 1);
64         th.detach();
65     }
66 
67     getchar();
68     return 0;
69 }

 

posted @ 2021-11-24 23:17  He_LiangLiang  阅读(77)  评论(0编辑  收藏  举报