用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字
云代码 - c++代码库

c++生产者消费者

2013-03-07 作者: 小蜜锋举报

[c++]代码库

// Copyright (C) 2001-2003
// William E. Kempf
//
//  Distributed under the Boost Software License, Version 1.0. (See accompanying
//  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//  生产者,消费者模式..


#include <boost/thread/condition.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/thread.hpp>
#include <iostream>
#include <vector>

class bounded_buffer : private boost::noncopyable
{
public:
	typedef boost::mutex::scoped_lock lock;
	bounded_buffer ( int n ) : begin ( 0 ), end ( 0 ), buffered ( 0 ), circular_buf ( n ) { }
	void send ( int m )
	{
		lock lk ( monitor );
		while ( buffered == circular_buf.size() )
			buffer_not_full.wait ( lk );
		circular_buf[end] = m;
		end = ( end+1 ) % circular_buf.size();
		++buffered;
		buffer_not_empty.notify_one();
	}
	int receive()
	{
		lock lk ( monitor );
		while ( buffered == 0 )
			buffer_not_empty.wait ( lk );
		int i = circular_buf[begin];
		begin = ( begin+1 ) % circular_buf.size();
		--buffered;
		buffer_not_full.notify_one();
		return i;
	}
private:
	int begin, end, buffered;
	std::vector<int> circular_buf;
	boost::condition buffer_not_full, buffer_not_empty;
	boost::mutex monitor;
};
bounded_buffer buf ( 2 );

void sender()
{
	int n = 0;
	while ( n < 100 )
	{
		buf.send ( n );
		std::cout << "sent: " << n << std::endl;
		++n;
	}
	buf.send ( -1 );
}

void receiver()
{
	int n;
	do
	{
		n = buf.receive();
		std::cout << "received: " << n << std::endl;
	}
	while ( n != -1 ); // -1 indicates end of buffer
}

int main()
{
	boost::thread thrd1 ( &sender );
	boost::thread thrd2 ( &receiver );
	thrd1.join();
	thrd2.join();
}


网友评论    (发表评论)

共1 条评论 1/1页

发表评论:

评论须知:

  • 1、评论每次加2分,每天上限为30;
  • 2、请文明用语,共同创建干净的技术交流环境;
  • 3、若被发现提交非法信息,评论将会被删除,并且给予扣分处理,严重者给予封号处理;
  • 4、请勿发布广告信息或其他无关评论,否则将会删除评论并扣分,严重者给予封号处理。


扫码下载

加载中,请稍后...

输入口令后可复制整站源码

加载中,请稍后...