生产者消费者问题c++
时间: 2023-10-18 21:05:07 浏览: 25
生产者消费者问题是一个经典的多线程编程问题。它包括两类线程,生产者和消费者,它们共享一个固定大小的缓冲区。生产者线程不断向缓冲区中添加数据,而消费者线程不断从缓冲区中取出数据。当缓冲区已满时,生产者线程必须等待直到有空间可用,而当缓冲区为空时,消费者线程必须等待直到有数据可用。
以下是一个简单的 C++ 实现:
``` c++
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
using namespace std;
const int BUFFER_SIZE = 10;
queue<int> buffer;
mutex mtx;
condition_variable not_full;
condition_variable not_empty;
void producer() {
for (int i = 1; i <= 20; ++i) {
unique_lock<mutex> lock(mtx);
not_full.wait(lock, [] { return buffer.size() != BUFFER_SIZE; });
buffer.push(i);
cout << "Produced: " << i << endl;
not_empty.notify_one();
}
}
void consumer() {
for (int i = 1; i <= 20; ++i) {
unique_lock<mutex> lock(mtx);
not_empty.wait(lock, [] { return !buffer.empty(); });
int num = buffer.front();
buffer.pop();
cout << "Consumed: " << num << endl;
not_full.notify_one();
}
}
int main() {
thread producer_thread(producer);
thread consumer_thread(consumer);
producer_thread.join();
consumer_thread.join();
return 0;
}
```
这个实现使用了一个互斥锁和两个条件变量。当缓冲区已满时,生产者线程会调用 `not_full.wait()` 等待空间可用,直到消费者线程调用 `not_full.notify_one()` 唤醒它。当缓冲区为空时,消费者线程会调用 `not_empty.wait()` 等待数据可用,直到生产者线程调用 `not_empty.notify_one()` 唤醒它。
需要注意的是,在生产者和消费者线程中,对缓冲区的访问需要加锁以确保线程安全。同时,在使用条件变量时,需要将加锁和等待条件的操作合并在一个 `unique_lock` 对象中,以确保在等待期间互斥锁被正确释放。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![text/x-c](https://img-home.csdnimg.cn/images/20210720083646.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![gz](https://img-home.csdnimg.cn/images/20210720083447.png)