concurrency - Concurrent blocking queue in C++11 -
for message passing in between threads, i'm looking concurrent queue following properties:
- bounded size
- pop method blocks/waits until element available.
- abort method cancel wait
- optional: priority
multiple producers, 1 consumer.
the concurrent_bounded_queue
of tbb provide that, i'm looking alternatives avoid additional dependency of tbb.
the application uses c++11 , boost. couldn't find suitable in boost. options?
naive implementation using boost library(circular_buffer) , 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_; };
Comments
Post a Comment