#include <iostream>
#include <mutex>
#include <queue>
#include <thread>
using namespace std;
//缓冲区大小
#define BufferSize 10
//使用缓冲区需要加锁
mutex mtxBuffer;
//条件变量,生产者等待缓冲区不为满,消费者等待缓冲区为满
condition_variable cvNotFull, cvFull;
//缓冲区
queue<int> buffer;
//产品编号
int i = 0;
void producer() {
unique_lock<mutex> ulock(mtxBuffer, defer_lock);
while (true) {
ulock.lock();
if (buffer.size() >= BufferSize) {
cvNotFull.wait(ulock, []() {
return buffer.size() < BufferSize;
});
}
cout << "生产者放入" << i << "产品" << endl;
buffer.push(i++);
//因为是死循环,并且notify是不解锁的,所以需要手动解锁,不然只能等到缓冲区满了wait解锁
//unlock在notify前后都可以
//notify是唤醒wait等待队列上的线程,需要重新抢锁,再判断条件(ctrl点进wait源码查看即可)
ulock.unlock();
cvFull.notify_one();
//睡眠,方便看输出
//否则想看消费者交替的情况需要调大BufferSize
//this_thread::sleep_for(chrono::milliseconds(100));
}
}
void consumer() {
unique_lock<mutex> ulock(mtxBuffer, defer_lock);
while (true) {
ulock.lock();
if (buffer.empty()) {
cvFull.wait(ulock, []() {
return !buffer.empty();
});
}
cout << "消费者" << this_thread::get_id() << "取出" << buffer.front() << "产品" << endl;
buffer.pop();
ulock.unlock();
cvNotFull.notify_one();
}
}
int main() {
thread Producer(producer);
thread Consumer1(consumer);
thread Consumer2(consumer);
thread Consumer3(consumer);
Producer.join();
Consumer1.join();
Consumer2.join();
Consumer3.join();
return 0;
}