【问题标题】:Concurrent blocking queue in C++11C++11中的并发阻塞队列
【发布时间】:2013-07-25 02:26:10
【问题描述】:

对于线程之间的消息传递,我正在寻找具有以下属性的并发队列:

  • 有界大小
  • 阻塞/等待直到元素可用的 pop 方法。
  • abort 方法取消等待
  • 可选:优先级

多个生产者,一个消费者。

TBB 的concurrent_bounded_queue 可以提供这一点,但我正在寻找替代方案以避免对 TBB 的额外依赖。

应用程序使用 C++11 和 boost。我找不到任何适合提升的东西。有哪些选择?

【问题讨论】:

  • 当然,这是一个选项。但是,我认为使用经过测试的实现总是比重新发明轮子更好。阻塞队列是很常见的事情,所以我首先想检查一下是否有我可以使用的代码。
  • 为什么一个新的建议库比 TBB 需要更少的依赖,它是一个额外的库
  • 是的,但在我的情况下 TBB 是有问题的(许可证,在交叉编译环境中使用)
  • @jcm 建立一个合适的并发队列不是一件容易的事。您需要指定它是多/单消费者和多/单生产者。你看过Boost.Lockfree吗?
  • 您可以使用condition_variable 对象轻松添加它。

标签: c++11 concurrency


【解决方案1】:

使用 Boost 库(循环缓冲区)和 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_;
};

【讨论】:

  • notify_one 在push 和pop 中也可以吗?哦,不应该是|| aborted_ 而不是&amp;&amp; !aborted_?
  • 我认为您必须在通知之前解锁互斥锁。
  • @filmor 好吧,我同意你的效率。这是一个天真的示例代码;P 我喜欢这种风格。 (仅供参考Why put Signal() inside the critical section?)
  • 要小心,因为在 std::condition_variable::wait 中可能会发生虚假唤醒。所以最好有while ( !q_.full() || aborted_) cv_pop_.wait( lk ) 和while ( !q_.empty() || aborted_ ) cv_push_.wait( lk )
  • @elvis.dukaj condition_variable::wait() with Predicate version 没有虚假唤醒。所以我更喜欢这个重载版本。
猜你喜欢
  • 2010-11-15
  • 1970-01-01
  • 2014-10-16
  • 1970-01-01
  • 1970-01-01
  • 2017-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多