对于线程之间传递的消息,我正在寻找具有以下属性的并发队列:
- 有界尺寸
- pop 方法会阻塞/等待直到元素可用。
- abort 方法取消等待
- 可选:优先
多个生产者,一个消费者。
The concurrent_bounded_queue
TBB 会提供这一点,但我正在寻找替代方案来避免 TBB 的额外依赖性。
该应用程序使用 C++11 和 boost。我在 boost 中找不到任何合适的东西。有什么选择?
使用 Boost 库(circular_buffer)和 C++11 标准库的简单实现。
#include <mutex>
#include <condition_variable>
#include <boost/circular_buffer.hpp>
struct operation_aborted {};
template <class T, std::size_t N>
class bound_queue {
public:
typedef T value_type;
bound_queue() : q_(N), aborted_(false) {}
void push(value_type data)
{
std::unique_lock<std::mutex> lk(mtx_);
cv_pop_.wait(lk, [=]{ return !q_.full() || aborted_; });
if (aborted_) throw operation_aborted();
q_.push_back(data);
cv_push_.notify_one();
}
value_type pop()
{
std::unique_lock<std::mutex> lk(mtx_);
cv_push_.wait(lk, [=]{ return !q_.empty() || aborted_; });
if (aborted_) throw operation_aborted();
value_type result = q_.front();
q_.pop_front();
cv_pop_.notify_one();
return result;
}
void abort()
{
std::lock_guard<std::mutex> lk(mtx_);
aborted_ = true;
cv_pop_.notify_all();
cv_push_.notify_all();
}
private:
boost::circular_buffer<value_type> q_;
bool aborted_;
std::mutex mtx_;
std::condition_variable cv_push_;
std::condition_variable cv_pop_;
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)