请帮我写一个生产者-消费者C++代码
时间: 2023-08-28 08:22:22 浏览: 118
好的,以下是一个基本的生产者-消费者模型的 C++ 代码:
```c++
#include <iostream>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <chrono>
using namespace std;
// 生产者-消费者模型中的缓冲区
queue<int> buffer;
// 互斥锁,用于保护缓冲区
mutex mtx;
// 条件变量,用于控制生产者和消费者的同步
condition_variable produce_cv, consume_cv;
// 生产者线程函数
void producer(int id)
{
while (true)
{
// 生成一个新的数据项
int item = rand() % 100;
// 获取互斥锁
unique_lock<mutex> lck(mtx);
// 如果缓冲区已满,则等待消费者消费数据
while (buffer.size() >= 10)
{
cout << "Producer " << id << " waiting..." << endl;
produce_cv.wait(lck);
}
// 将数据项加入缓冲区
buffer.push(item);
cout << "Producer " << id << " produced item " << item << endl;
// 通知消费者有新的数据可供消费
consume_cv.notify_one();
// 释放互斥锁
lck.unlock();
// 生产者线程休眠一段时间,模拟生产过程
this_thread::sleep_for(chrono::milliseconds(rand() % 1000));
}
}
// 消费者线程函数
void consumer(int id)
{
while (true)
{
// 获取互斥锁
unique_lock<mutex> lck(mtx);
// 如果缓冲区为空,则等待生产者生产数据
while (buffer.empty())
{
cout << "Consumer " << id << " waiting..." << endl;
consume_cv.wait(lck);
}
// 从缓冲区中取出一项数据
int item = buffer.front();
buffer.pop();
cout << "Consumer " << id << " consumed item " << item << endl;
// 通知生产者有新的空闲空间可供生产
produce_cv.notify_one();
// 释放互斥锁
lck.unlock();
// 消费者线程休眠一段时间,模拟消费过程
this_thread::sleep_for(chrono::milliseconds(rand() % 1000));
}
}
int main()
{
// 创建两个生产者线程和两个消费者线程
thread p1(producer, 1);
thread p2(producer, 2);
thread c1(consumer, 1);
thread c2(consumer, 2);
// 等待所有线程执行完毕
p1.join();
p2.join();
c1.join();
c2.join();
return 0;
}
```
上述代码中,生产者和消费者线程都是通过无限循环来模拟实际生产和消费的过程。当缓冲区已满时,生产者线程会等待消费者线程消费数据;当缓冲区为空时,消费者线程会等待生产者线程生产数据。
注意,在生产者和消费者线程中,我们都使用了一个 `unique_lock` 对象来获取互斥锁,并在必要时释放锁。当生产者线程将新的数据项加入缓冲区之后,它会通过条件变量 `consume_cv` 通知消费者线程有新的数据可供消费;而当消费者线程从缓冲区中取出一项数据之后,它会通过条件变量 `produce_cv` 通知生产者线程有新的空闲空间可供生产。这样,生产者和消费者线程之间就可以实现同步。
阅读全文
相关推荐














