#include <condition_variable>
#include <iostream>
#include <mutex>
#include <string>
#include <thread>
#include <vector>
std::vector<int> g_storeHouse; // 仓库
const int g_storeHouseSize = 5; // 仓库容量
int g_nCount = 0;
const int g_maxCount = 100;
std::mutex g_mut;
std::condition_variable g_cond;
class Productor {
public:
void Product() {
while (g_nCount < 100) {
std::unique_lock<std::mutex> lock(g_mut);
g_cond.wait(lock, [&] { return g_storeHouse.size() < g_storeHouseSize; });
g_storeHouse.push_back(++g_nCount);
std::cout << "product " << g_nCount << std::endl;
lock.unlock();
g_cond.notify_one();
}
}
};
class Consumer {
public:
void Consume(int id) {
while (g_nCount < 100) {
std::unique_lock<std::mutex> lock(g_mut);
g_cond.wait(lock, [&] { return !g_storeHouse.empty() || g_nCount >= 100; });
// 消费者的g_nCount计数需要到105,才能完全消费完
if (g_nCount > g_maxCount + g_storeHouseSize) {
break;
} else if (g_nCount > g_maxCount) {
++g_nCount;
}
std::cout << "Consume" << id << " " << g_storeHouse.back() << std::endl;
g_storeHouse.pop_back();
lock.unlock();
g_cond.notify_one();
}
}
};
int main() {
Productor pd;
Consumer cm;
std::thread thd1(&Productor::Product, pd);
std::thread thd2(&Consumer::Consume, cm, 1);
std::thread thd3(&Consumer::Consume, cm, 2);
thd1.join();
thd2.join();
thd3.join();
return 0;
}
使用c++11,实现一个生产者-消费者模型
最新推荐文章于 2024-07-23 10:19:57 发布