基于boost 线程并行技术实现消息队列方式

tan625747 2011-08-18 11:52:12
小立再也没有机会,就这样失去,人生当中最大的悲哀莫过于此。才发现原来生活就是这么的槽糕,所有的都是没有劲的。

    翻遍csdn,也翻遍博客园,更翻遍google 中文,翻遍英文只有两篇。就以此文献给这些堕落的,颓废的,乱七八槽的日子吧。


#include <queue>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/thread.hpp>
#include <boost/thread/tss.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>


#include <iostream>
using namespace std;
using namespace boost;


boost::recursive_mutex io_mutex;
boost::condition_variable_any cond;
std::queue<int> iq;

class printer
{
public:
printer(boost::asio::io_service& io,int n)
: strand_(io),
timer1_(io, boost::posix_time::seconds(1)),
timer2_(io, boost::posix_time::seconds(1)),
count_(n)
{
timer2_.async_wait(boost::bind(&printer::enqueue, this));
timer1_.async_wait(boost::bind(&printer::dequeue, this));

}

~printer()
{
boost::recursive_mutex::scoped_lock lock(io_mutex);
std::cout << "Final count is " << count_ << "\n";
}

void dequeue()
{
boost::recursive_mutex::scoped_lock lock(io_mutex);
while(iq.empty())
{
cond.wait(lock);

}
int pop =0;
if (!iq.empty())
{
pop = iq.front();
iq.pop();
cout<<"------------pop "<<pop<<endl;
}
cond.notify_all();

timer1_.expires_at(timer1_.expires_at() + boost::posix_time::seconds(1));
timer1_.async_wait(boost::bind(&printer::dequeue, this));
}

void enqueue()
{
boost::recursive_mutex::scoped_lock lock(io_mutex);

while(iq.size() == 1000)
{
cond.wait(lock);
}

iq.push(count_);;
cond.notify_all();
cout<<"------------push "<<count_<<endl;
timer1_.expires_at(timer1_.expires_at() + boost::posix_time::seconds(1));
timer1_.async_wait(boost::bind(&printer::enqueue, this));
}

private:
boost::asio::strand strand_;
boost::asio::deadline_timer timer1_;
boost::asio::deadline_timer timer2_;
int count_;
};


int main()
{
thread_group threads;
boost::asio::io_service io;


printer * p[1000];
int num = 1000;
for(int i = 0; i < num; i++)
{
p[i] = new printer(io,i);

threads.create_thread(boost::bind(&boost::asio::io_service::run, &io));
}


io.run();
threads.join_all();


std::system("pause");
return 0;
}
...全文
671 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
hongbin7698 2011-10-12
  • 打赏
  • 举报
回复
好贴,留名。
AlanBruce 2011-08-23
  • 打赏
  • 举报
回复
Mark!
cunyan_0519 2011-08-18
  • 打赏
  • 举报
回复
什么和什么???

64,636

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧