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 }

 

posted @ 2018-03-12 16:47  喵小喵~  阅读(119)  评论(0编辑  收藏  举报