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

综合应用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();
}

运行结果为:

这里写图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值