zoukankan      html  css  js  c++  java
  • 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 }

     

     

    作者:小乌龟
    【转载请注明出处,欢迎转载】 希望这篇文章能帮到你

     

  • 相关阅读:
    城市承灾体脆弱性和易损性的影响因素
    《风暴潮、海浪、海啸和海冰灾害应急预案》
    承灾体
    ArcGIS数据存储的方式
    ArcGIS几种数据格式2
    ArcGIS几种数据格式
    【ArcGIS】文件地理数据库,个人地理数据库与ArcSDE的局别
    dojo事件绑定
    Spark最简安装
    Spark 概述
  • 原文地址:https://www.cnblogs.com/music-liang/p/15600830.html
Copyright © 2011-2022 走看看