c++写一个生产者消费者模型
时间: 2024-03-05 09:50:10 浏览: 30
下面是一个基于 C++11 的生产者消费者模型的实现:
```
#include <iostream>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
const int kBufferSize = 10;
std::queue<int> buffer;
std::mutex buffer_mutex;
std::condition_variable buffer_not_empty;
std::condition_variable buffer_not_full;
void Producer() {
for (int i = 0; i < 100; ++i) {
std::unique_lock<std::mutex> lock(buffer_mutex);
buffer_not_full.wait(lock, []{ return buffer.size() < kBufferSize; });
buffer.push(i);
std::cout << "Producer produced " << i << ".\n";
buffer_not_empty.notify_one();
}
}
void Consumer() {
for (int i = 0; i < 100; ++i) {
std::unique_lock<std::mutex> lock(buffer_mutex);
buffer_not_empty.wait(lock, []{ return !buffer.empty(); });
int value = buffer.front();
buffer.pop();
std::cout << "Consumer consumed " << value << ".\n";
buffer_not_full.notify_one();
}
}
int main() {
std::thread producer(Producer);
std::thread consumer(Consumer);
producer.join();
consumer.join();
return 0;
}
```
这个例子中,生产者不断地往 buffer 中添加数据,当 buffer 已满时就等待消费者取走数据,消费者不断地从 buffer 中取出数据,当 buffer 已空时就等待生产者添加数据。
其中,buffer_mutex 是用来保护 buffer 的互斥锁,buffer_not_empty 和 buffer_not_full 分别是用来通知消费者和生产者的条件变量。当 buffer_not_empty.wait() 被调用时,线程会等待直到 buffer 不为空,buffer_not_full.wait() 同理。notify_one() 则是用来通知等待线程有新的数据或者空间可用。