zoukankan      html  css  js  c++  java
  • 41.C++多线程生产消费者模型

     1 #include <iostream>
     2 #include <thread>
     3 #include <mutex>
     4 #include <condition_variable>
     5 #include <array>
     6 #include <vector>
     7 using namespace std;
     8 
     9 //通过mutex 等待事件响应
    10 condition_variable isfull, isempty;//处理两种情况
    11 mutex m;
    12 bool flag = true;//标识,消费完了就退出
    13 vector<int> myint;//开辟十个元素
    14 
    15 void put(int num)
    16 {
    17     for (int i = 0; i < num; i++)
    18     {
    19         unique_lock<mutex> lk(m);//锁定
    20         while (myint.size() >= 10)
    21         {
    22             //一直等待有空位才生产
    23             isempty.wait(lk);
    24         }
    25 
    26         myint.push_back(i);
    27         cout << "生产了" << i << endl;
    28         //激活isfull
    29         isfull.notify_all();
    30         
    31         this_thread::sleep_for(chrono::milliseconds(500));
    32     }
    33     flag = false;
    34 }
    35 
    36 void take()
    37 {
    38     while (flag)
    39     {
    40         unique_lock<mutex> lk(m);//锁定
    41         while (myint.size() == 0)
    42         {
    43             //一直等待有生产后才执行,(等待到激活后才可以执行)
    44             isfull.wait(lk);
    45         }
    46 
    47         if (flag)
    48         {
    49             cout << "消费了" << myint[myint.size() - 1] << endl;
    50             myint.pop_back();//消除
    51             //激活isempty
    52             isempty.notify_all();
    53         }
    54     }
    55 }
    56 
    57 void main()
    58 {
    59     thread t1(take);
    60     thread t2(take);
    61     thread t3(take);
    62     thread t4(put,100);
    63     cin.get();
    64 }
  • 相关阅读:
    页面生命周期
    设计模式
    算法
    window服务
    Xml
    sql声明变量,及if else语句、while语句的用法
    SQL 使用临时表和临时变量完成update表字段实际案例
    SQL Server遍历表的几种方法
    node快速构建express项目
    词法分析
  • 原文地址:https://www.cnblogs.com/xiaochi/p/8550158.html
Copyright © 2011-2022 走看看