C ++ 11中的并发阻塞队列

编程入门 行业动态 更新时间:2024-10-10 13:18:33
本文介绍了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中的并发阻塞队列

本文发布于:2023-11-26 09:21:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1633540.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:队列

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!