您的位置:首页 > 其它

条件变量实例:生产者-消费者模式的后进先出型(std::stack)缓冲区

2016-07-16 01:04 309 查看
综合应用boost::thread库(thread, mutex, condition_variable_any)实现的 生产者-消费者模式

后进先出型(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