生产者消费者模型-c++实现

笔者最近在修改client的scan逻辑,用到了生产消费模型,因此写来写了中这个示例代码。

#include <bits/stdc++.h>
using namespace std;

class BoundedBuffer {
 public:
  explicit BoundedBuffer(std::size_t size) : begin_(0), end_(0), length_(0) {
    container_.resize(size);
  }

  void Produce(int n) {
    std::unique_lock<std::mutex> lck(mutex_);
    con_pro_.wait(lck, [&] {
      return length_ < container_.size();
    });
    container_[end_] = n;
    end_ = (end_ + 1) % container_.size();
    length_++;
    con_con_.notify_one();
  };

  int Consume() {
    std::unique_lock<std::mutex> lck(mutex_);
    con_con_.wait(lck, [&] {
      return length_ > 0;
    });
    int ret = container_[begin_];
    begin_ = (begin_ + 1) % container_.size();
    length_--;
    con_pro_.notify_one();
    return ret;
  };

  bool empty() const {
    return length_ == 0;
  }

  std::size_t size() const {
    return length_;
  }

 private:
  size_t begin_;
  size_t end_;
  size_t length_;
  std::mutex mutex_;
  std::condition_variable con_pro_;
  std::condition_variable con_con_;
  std::vector<int> container_;
};

int main() {
  BoundedBuffer buffer(5);
  std::vector<std::shared_ptr<std::thread>> produce_jobs;
  auto produce_job = [&]() -> void {
    for (int i = 0; i < 10; i++) {
      buffer.Produce(i);
    }
  };

  produce_jobs.reserve(10);
  for (int i = 0; i < 10; i++) {
    produce_jobs.emplace_back(std::make_shared<std::thread>(produce_job));
  }

  while (!buffer.empty()) {
    std::cout << buffer.Consume() << std::endl;
  }

  for (auto &job : produce_jobs) {
    job->join();
  }
};
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值