本文介绍了C ++ 11中的并发阻塞队列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对于在线程之间传递的消息,我正在寻找具有以下属性的并发队列:
For message passing in between threads, I'm looking for a concurrent queue with following properties:
- 退出方法以取消等待
- 可选:优先级
多个生产者,一个消费者。
Multiple producers, one consumer.
concurrent_bounded_queue 的TBB会提供,但我正在寻找替代方案,以避免TBB的额外依赖。
The concurrent_bounded_queue of TBB would provide that, but I'm looking for alternatives to avoid the additional dependency of TBB.
应用程序使用C + +11和提升。我找不到任何合适的助推器。
The application uses C++11 and boost. I couldn't find anything suitable in boost. What are the options?
推荐答案使用Boost库(circular_buffer)和C ++ 11标准库的朴素实现。
Naive implementation using Boost library(circular_buffer) and C++11 standard library.
#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_; };更多推荐
C ++ 11中的并发阻塞队列
发布评论