C++实现一个简易的生产者消费者模式
1 #include <bits/stdc++.h> 2 #include <mutex> 3 using namespace std; 4 #define maxn 10 5 mutex m; 6 condition_variable full_con; //缓冲池已满,让full_con等待 7 condition_variable empty_con; //缓冲池为空,让empty等待 8 string buf[maxn]; //建立能容纳maxn个的缓冲池 9 int pro_num = 0; //记录生产者在缓冲池的位置 10 int con_num = 0; //记录消费者在缓冲池的位置 11 int pro_idx = 0; //记录第几个被生产者生产的商品 12 class producer { 13 private: 14 string in; // 生产的产品 15 int idx; // 标记现在是第几个生产者 16 public: 17 producer(string in = "", int idx = 0) : in(in), idx(idx) {} 18 ~producer() = default; 19 20 void produce() { 21 in = "生产者" + to_string(this->idx) + "生产产品" + to_string(pro_idx++); 22 unique_lock<mutex> lock(m); 23 while ((pro_num + 1) % maxn == con_num) { 24 cout << "缓冲池已满,生产者 " << idx << " 在等待一个空位" << endl; 25 full_con.wait(lock); 26 } 27 buf[pro_num] = in; 28 pro_num = (pro_num + 1) % maxn; 29 cout << in << endl; 30 empty_con.notify_all(); //唤醒empty 31 } 32 }; 33 34 class consumer { 35 private: 36 string out; 37 int idx; 38 public: 39 consumer(string out = "",int idx = 0) : out(out) , idx(idx){} 40 ~consumer() = default; 41 void consume() { 42 unique_lock<mutex> lock(m); 43 while (pro_num == con_num) { 44 cout << "缓冲池为空,消费者" << idx << "在等待商品" << endl; 45 empty_con.wait(lock); 46 } 47 out = "消费者" + to_string(this->idx) + "消费了" + buf[con_num]; //消费者消费了产品 48 con_num = (con_num + 1) % maxn; 49 cout << out << endl; 50 full_con.notify_all(); // 唤醒full 51 } 52 }; 53 void producer_work(producer p) { //生产者生产50次产品 54 int i = 0; 55 while(i < 50){ 56 p.produce();i++; 57 } 58 } 59 void consumer_work(consumer c) { //消费者消费50次产品 60 int i = 0; 61 while (i < 50) { 62 c.consume();i++; 63 } 64 } 65 int main() 66 { 67 producer p; 68 consumer c; 69 thread pro(producer_work, p); 70 thread con(consumer_work, c); 71 pro.join(); 72 con.join(); 73 return 0; 74 }