读者写者问题的C++实现(使用boost)

参考链接:http://stlchina.huhoo.net/twiki/bin/view.pl/Main/BoostThread

/*
	@description 读者写者问题的实现
	1.使用scoped_lock对成员变量Mutex加锁,实现对象的互斥访问(也就是缓冲数组的互斥访问)
	2.使用scoped_lock对std::cout互斥访问
	3.当A线程等待时,应该对mutex解锁,以使B线程能够访问缓冲区,然后唤醒A,因此使用con.wait(slock);
	来阻塞当前线程并解开缓冲锁
**/

#include <iostream>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition.hpp>
#include <boost/thread/thread.hpp>
using namespace std;
const int BUFFER_SIZE = 10;
const int SEND_CNT = 100;
boost::mutex io_mutex;
class buffer{
public:
	buffer():p(0),g(0),full(0){}

	void put(int n){
		boost::mutex::scoped_lock slock(mutex);
		if(full == BUFFER_SIZE){
			{
				boost::mutex::scoped_lock lock(io_mutex);
				cout<<"buffer is full.waiting..."<<endl;
			}
			while(full == BUFFER_SIZE)
				con.wait(slock);
		}
		buf[p] = n;
		p = (p + 1) % BUFFER_SIZE;
		full++;
		con.notify_one();
	}
	int get(){
		boost::mutex::scoped_lock slock(mutex);
		if(full == 0){
			{
				boost::mutex::scoped_lock slock(io_mutex);
				cout<<"buffer is empty.waiting..."<<endl;
			}
			while(full == 0)
				con.wait(slock);
		}
		int x = buf[g];
		g = (g + 1) % BUFFER_SIZE;
		full--;
		con.notify_one();
		return x;
	}
private:
	int full;
	boost::condition con;
	boost::mutex mutex;
	int buf[SEND_CNT];
	int p,g;
};
buffer buff;

void writer(){
	for(int i = 0;i < SEND_CNT;++i){
		{
			boost::mutex::scoped_lock lock(io_mutex);
			cout<<"sending :"<<i<<endl;
		}
		buff.put(i);
	}
}

void reader(){
	for(int i = 0;i < SEND_CNT;i++){
		int x  = buff.get();
		{
			boost::mutex::scoped_lock lock(io_mutex);
			cout<<"reading :"<<x<<endl;
		}
	}
}
int main(int argc,char* argv[])
{
	boost::thread thr1(boost::bind(&writer));
	boost::thread thr2(boost::bind(&reader));
	thr1.join();
	thr2.join();
	system("pause");
	return 0;
}

初学boost,错误之处,敬请指正,感激不尽。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值