#include <iostream>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
std::queue<int> buffer; // 共享缓冲区
const int bufferSize = 5; // 缓冲区大小
std::mutex mtx; // 互斥锁
std::condition_variable cv_producer, cv_consumer; // 条件变量
void Producer()
{
for (int i = 1; i <= 10; ++i) {
std::unique_lock<std::mutex> lock(mtx); // 获取互斥锁
// 如果缓冲区已满,则等待消费者消耗数据
while (buffer.size() >= bufferSize)
cv_producer.wait(lock);
buffer.push(i);
std::cout << "Produced: " << i << std::endl;
cv_consumer.notify_one(); // 通知消费者可以消费数据
}
}
void Consumer()
{
for (int i = 1; i <= 10; ++i) {
std::unique_lock<std::mutex> lock(mtx); // 获取互斥锁
// 如果缓冲区为空,则等待生产者生产数据
while (buffer.empty())
cv_consumer.wait(lock);
int data = buffer.front();
buffer.pop();
std::cout << "Consumed: " << data << std::endl;
cv_producer.notify_one(); // 通知生产者可以生产数据
}
}
int main()
{
std::thread producerThread(Producer);
std::thread consumerThread(Consumer);
producerThread.join();
consumerThread.join();
return 0;
}
C++简单实现生产者与消费者模式
最新推荐文章于 2024-06-16 15:09:43 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)