使用boost条件变量实现消息队列
2015-10-10 09:19
92 查看
boost
thread库里面没有实现类似java中BlockingQueue的东东。但是使用条件变量来实现一个还是很容易的。下面的代码是以前学习boost
thread库时的练手之作。
==============================================================
#include
<boost/shared_array.hpp>
#include <boost/thread.hpp>
#include <stdexcept>
#include <queue>
class MsgQueue
{
public:
typedef
boost::shared_array<char>
Msg;
MsgQueue(std::size_t
max_size_)
:
max_size(max_size_)
, close_flag(false)
{
if (max_size <
1)
{
throw
std::runtime_error("MsgQueue::MsgQueue
: max_size < 1");
}
}
~MsgQueue()
{
close();
}
void push(Msg msg)
{
boost::mutex::scoped_lock
lock(mtx);
while (msgs.size()
>= max_size &&
!close_flag)
{
full_cond.wait(lock);
}
if (close_flag)
{
throw
std::runtime_error("MsgQueue::push
: msg queue has been shutdown.");
}
msgs.push(msg);
if(msgs.size() == 1)
{
empty_cond.notify_all();
}
}
bool nbPush(Msg msg)
{
//
non-blocking push
boost::mutex::scoped_lock
lock(mtx);
if (msgs.size()
>= max_size || close_flag)
{
return
false;
}
msgs.push(msg);
thread库里面没有实现类似java中BlockingQueue的东东。但是使用条件变量来实现一个还是很容易的。下面的代码是以前学习boost
thread库时的练手之作。
==============================================================
#include
<boost/shared_array.hpp>
#include <boost/thread.hpp>
#include <stdexcept>
#include <queue>
class MsgQueue
{
public:
typedef
boost::shared_array<char>
Msg;
MsgQueue(std::size_t
max_size_)
:
max_size(max_size_)
, close_flag(false)
{
if (max_size <
1)
{
throw
std::runtime_error("MsgQueue::MsgQueue
: max_size < 1");
}
}
~MsgQueue()
{
close();
}
void push(Msg msg)
{
boost::mutex::scoped_lock
lock(mtx);
while (msgs.size()
>= max_size &&
!close_flag)
{
full_cond.wait(lock);
}
if (close_flag)
{
throw
std::runtime_error("MsgQueue::push
: msg queue has been shutdown.");
}
msgs.push(msg);
if(msgs.size() == 1)
{
empty_cond.notify_all();
}
}
bool nbPush(Msg msg)
{
//
non-blocking push
boost::mutex::scoped_lock
lock(mtx);
if (msgs.size()
>= max_size || close_flag)
{
return
false;
}
msgs.push(msg);
相关文章推荐
- 并行计算:近来语言发展的趋势和我…
- 转载:C, Erlang, Java and Go Web…
- c++中实现类似java printStackTrac…
- ASCII字符随机混淆字典的生成
- 端口复用(SO_REUSEADDR)是干啥用的…
- 正确实现和使用assert
- 《C陷阱与缺陷》书评兼感想
- RAII、异常、构造函数是一家人
- 一个笑话和其对开发的启示
- 并发环境下的单态——应用程序级单态…
- 《软件随想录》的随想
- 转载:敏捷估计和规划的12条指导原…
- 《设计模式》旧书重读和总结:创建…
- scrum-and-xp读书笔记
- error C2533: 构造函数不能有返回类型
- shell脚本 整数比较
- Go之对象拷贝
- 代码复用之道:回调机制及c++实现…
- 对候选字排列组合后输出的程序(用…
- boost::bind示例