c++创建多个(不少于5个)进程或者线程模拟生产者和消费者
时间: 2024-02-13 16:03:49 浏览: 33
好的,我可以给您提供一个C++多线程实现生产者消费者的例子。
```cpp
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
using namespace std;
const int kItemCount = 10; // 生产的物品数量
const int kBufferSize = 5; // 缓冲区大小
queue<int> buffer; // 缓冲区
mutex mtx; // 互斥锁
condition_variable cv; // 条件变量
void producer(int id) {
for (int i = 1; i <= kItemCount; i++) {
unique_lock<mutex> lock(mtx);
// 如果缓冲区已满则等待
cv.wait(lock, [] { return buffer.size() < kBufferSize; });
int item = rand() % 100 + 1; // 生产一个物品
buffer.push(item); // 放入缓冲区
cout << "Producer " << id << " produced item " << item << endl;
cv.notify_all(); // 通知消费者
}
}
void consumer(int id) {
while (true) {
unique_lock<mutex> lock(mtx);
// 如果缓冲区为空则等待
cv.wait(lock, [] { return !buffer.empty(); });
int item = buffer.front(); // 取出一个物品
buffer.pop(); // 从缓冲区中删除
cout << "Consumer " << id << " consumed item " << item << endl;
cv.notify_all(); // 通知生产者
if (buffer.empty() && item == kItemCount) break; // 如果缓冲区已清空并且消费者已消费完所有物品,则退出循环
}
}
int main() {
// 创建生产者线程
thread producers[5];
for (int i = 0; i < 5; i++) {
producers[i] = thread(producer, i + 1);
}
// 创建消费者线程
thread consumers[5];
for (int i = 0; i < 5; i++) {
consumers[i] = thread(consumer, i + 1);
}
// 等待生产者线程和消费者线程执行完成
for (int i = 0; i < 5; i++) {
producers[i].join();
consumers[i].join();
}
cout << "All items have been produced and consumed." << endl;
return 0;
}
```
这个例子中,我们创建了5个生产者线程和5个消费者线程,每个生产者线程会生产10个物品并将其放入缓冲区,每个消费者线程会从缓冲区中取出物品并将其消费掉。程序最终会输出"All items have been produced and consumed."表示所有物品都已经被生产和消费完毕。
相关推荐
![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)
![](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)
![](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)
![](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)