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

#include 
#include 
#include 
#include 
#include 
#include 

std::vector 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 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 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,多线程)