栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

#include 
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 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 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 container_;
};

int main() {
  BoundedBuffer buffer(5);
  std::vector> 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(produce_job));
  }

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

  for (auto &job : produce_jobs) {
    job->join();
  }
};
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1037451.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号