条件变量实例:生产者-消费者模式的后进先出型(std::stack)缓冲区
2016-07-16 01:04
309 查看
综合应用boost::thread库(thread, mutex, condition_variable_any)实现的 生产者-消费者模式
后进先出型(std::stack)缓冲区
stack可以经过轻微修改使用队列替换。
运行结果为:
后进先出型(std::stack)缓冲区
stack可以经过轻微修改使用队列替换。
#include <boost/thread.hpp> using namespace boost; #include <stack> #include <iostream> using std::stack; using std::cout; using std::endl; //生产者-消费者模式的后进先出型(std::stack)缓冲区 class Buffer { public: //构造函数 Buffer(size_t n) :un_read(0), capacity(n){} //写入数据x void put(int x){ //局部域 { mutex::scoped_lock lock(mu); //锁定互斥量 while (is_full()){ cond_put.wait(mu); //条件变量等待 } stk.push(x); //写入数据 ++un_read; } //解锁互斥量 cond_get.notify_one(); //通知可以读取数据 } //读取数据 void get(int *x){ { mutex::scoped_lock lock(mu); while (is_empty()){ cond_get.wait(mu); } *x = stk.top(); stk.pop(); --un_read; } cond_put.notify_one(); } private: //判断缓冲区是否满 bool is_full(){ return un_read == capacity; } //判断缓冲区是否为空 bool is_empty(){ return un_read == 0; } private: mutex mu; //互斥量,配合条件变量使用 condition_variable_any cond_put; //写入条件变量 condition_variable_any cond_get; //读取条件变量 stack<int> stk; //缓冲区对象 int un_read; int capacity; }; Buffer buf(5); //定义一个缓冲区对象 mutex io_mu_; //定义一个输出互斥量 //生产者,n个 void producer(int n) { for (int i = 0; i < n; i++){ //输出信息 { mutex::scoped_lock lock(io_mu_); cout << "put " << i <<" to buffer"<< endl; } buf.put(i); //写入数据 } } //消费者 void consumer(int n) { int result(0); for (int i = 0; i < n; i++){ { buf.get(&result); //读取数据 mutex::scoped_lock lock(io_mu_); cout << "get " << result << " from buffer" << endl; } } } void producer_consumer_test() { thread t_producer(producer, 20); thread t_consumer1(consumer, 10); thread t_consumer2(consumer, 10); t_producer.join(); t_consumer1.join(); t_consumer2.join(); }
运行结果为:
相关文章推荐
- boost相关小知识(长期顶置更新)
- C++单元测试:boost.test
- boost asio学习笔记 [1] - 同步通讯
- boost_asio学习笔记[2] - 客户端异步通讯
- boost::flat_map性能测试
- Ubuntu下如何安装boost?
- How to get a boost::shared_ptr from this
- boost 库 enable_shared_from_this 实现原理分析
- boost bind使用指南
- 最常用的两种C++序列化方案的使用心得
- 使用boost进行CRC64计算
- [网络开发]boost::asio简介
- Windows下如何编译使用boost?
- Boost库学习(0)
- Boost库学习(1)log和unittest
- Boost库学习(2)thread 1
- Boost库学习(3)thread 2
- Boost库学习(4)thread 3
- Boost库学习(6)filesystem
- Boost库学习(7)regex