4、多生产者多消费者模式:
- 该模型可以说是前面两种模型的综合,程序需要维护两个计数器,分别是生产者已生产产品的数目和消费者已取走产品的数目。另外也需要保护产品库在多个生产者和多个消费者互斥地访问。
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <deque>
using namespace std;
static const int kItemsToProduce = 20;
std::mutex stdoutMutex;
struct ItemRepository
{
deque<int> itemQueue;
int MaxSize = 10;
int producedItemCounter = 0;
int consumedItemCounter = 0;
std::mutex mtx;
std::mutex producedItemCounterMtx;
std::mutex consumedItemCounterMtx;
std::condition_variable repository_notFull;
std::condition_variable repository_notEmpty;
}gItemRepository;
typedef struct ItemRepository ItemRepository;
void ProduceItem(ItemRepository &itemRepo, int item)
{
std::unique_lock<std::mutex> lock(itemRepo.mtx);
itemRepo.repository_notFull.wait(lock, [&itemRepo] {
bool full = itemRepo.itemQueue.size() >= itemRepo.MaxSize;
if (full)
{
std::lock_guard<std::mutex> lock(stdoutMutex);
cout << "仓库满了,生产者等待中..." << "thread id = " << std::this_thread::get_id() << en