#include <iostream>
#include <queue>
#include <thread>
#include <mutex>
#include <unistd.h>
#include <condition_variable>
using namespace std;
#define MAXSIZE 20
mutex mtx;
condition_variable produce, consume;
queue<int> q;
void producer(int id) {
while (true) {
sleep(1);
unique_lock<mutex> lck(mtx); // 上锁
while (q.size() == MAXSIZE) { // 队列满了
produce.wait(lck);
}
q.push(id); // 生产
consume.notify_all(); // 生产完一个,通知消费者继续消费
lck.unlock(); // 解锁
}
}
void consumer() {
while (true) {
sleep(1);
unique_lock<mutex> lck(mtx); // 上锁
// 判断队列是否为空的时候,使用的是while(q.size()==0),而不是if(q.size()==0)
// wait()从阻塞到返回,可能由于系统的不确定原因唤醒,即伪唤醒
while (q.size() == 0) { // 队列为空
// 消费完所有,调用wait函数会对lck进行解锁,让生产者继续生产
// consume被唤醒后,会继续进行加锁
consume.wait(lck);
}
q.pop(); // 消费
produce.notify_all(); // 消费完一个,通知生产者继续生产
lck.unlock(); // 解锁
}
}
int main() {
thread consumers[2], producers[2];
for (int i = 0; i < 2; ++i) {
producers[i] = thread(producer, i + 1);
consumers[i] = thread(consumer);
}
for (int i = 0; i < 2; ++i) {
producers[i].join();
consumers[i].join();
}
system("pause");
return 0;
}