使用c++11,实现一个生产者-消费者模型

#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;
}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值