LinuxC/C++编程基础(8) 基于条件变量实现生产者与消费者的实例

一.buffer.h的声明,如下:

#ifndef BUFFER_H
#define BUFFER_H


#include <iostream>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition_variable.hpp>
#include <stack>

class buffer{
public:
buffer(size_t n):unRead(0),capacity(n){}
void put(int x);
void get(int* x);
private:
bool is_full();
bool is_empty();
private:
boost::mutex mu;
boost::condition_variable_any putCond;
boost::condition_variable_any getCond;
std::stack<int> stk;
int unRead;
int capacity;
};


inline bool buffer::is_full(){
return unRead == capacity;
}


inline bool buffer::is_empty(){
return unRead == 0;
}


#endif
转正请注明出处:山水间博客:http://blog.csdn.net/linyanwen99/article/details/8227020
二.buffer.cpp的实现,如下:

#include "buffer.h"


boost::mutex io_mu;
void buffer::put(int x)
{
{
boost::mutex::scoped_lock lock(mu);
while(is_full())
{
{
boost::mutex::scoped_lock lock(io_mu);//io流是共享资源,不是线程安全的,故需要锁定,以下同理。
std::cout<<"stack is full,please wait..."<<std::endl;
}
putCond.wait(mu);
}
stk.push(x);
++unRead;
}
getCond.notify_one();
}


void buffer::get(int* x)
{
{
boost::mutex::scoped_lock lock(mu);
while(is_empty())
{
{
boost::mutex::scoped_lock lock(io_mu);
std::cout<<"stack is empty,please wait..."<<std::endl;
}
getCond.wait(mu);
}
--unRead;
*x = stk.top();
stk.pop();
}
putCond.notify_one();
}

转正请注明出处:山水间博客:http://blog.csdn.net/linyanwen99/article/details/8227020

三.main.cpp的实现,如下:

#include <boost/thread/thread.hpp>
#include <string>
#include "buffer.h"
extern boost::mutex io_mu;
buffer buf(5);
void producer(int n,std::string str,int seq)
{
for(int i=0;i<n;++i)
{
{
boost::mutex::scoped_lock lock(io_mu);
std::cout<<"["<<str<<"->"<<seq<<"]"<<" put data "<<i<<std::endl;
}
buf.put(i);
sleep(1);
}
}


void consumer(int n,std::string str,int seq)
{
int x;
for(int i=0;i<n;++i)
{
buf.get(&x);
boost::mutex::scoped_lock lock(io_mu);
std::cout<<"["<<str<<"->"<<seq<<"]"<<" get data "<<x<<std::endl;
sleep(1);
}
}


int main(int argc,char** argv)
{
boost::thread t1(producer,10,"producer",1);
boost::thread t2(consumer,5,"consumer",1);
boost::thread t3(consumer,5,"consumer",2);

t1.join();
t2.join();
t3.join();

return 0;
}


说明:代码简洁明了,无需赘述。


四.可能会出现的问题,如下:

 undefined reference to `boost::thread_resource_error::thread_resource_error()'

说明:该问题其实很好解决,当然也得看具体情况,这里略去。


五.makefile的编写请参考前一篇


参考文献:boost库完全开发指南,罗剑锋 著

转正请注明出处:山水间博客:http://blog.csdn.net/linyanwen99/article/details/8227020


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值