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

标签 c++11 concurrency

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

  • 有界尺寸
  • 阻止/等待元素可用的 pop 方法。
  • abort 方法取消等待
  • 可选:优先级

  • 多个生产者,一个消费者。
    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_;
    };
    

    关于c++11 - C++11中的并发阻塞队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17853875/

    相关文章:

    java - ConcurrentModificationException 在 Java 中递归使用 Maps

    c++ - 字符串与十六进制值的用户定义文字

    c++11 - 在移动构造函数中使用 std::move

    c++ - undefined reference 捕获 lambda 中的静态变量

    Java 使列表线程的副本安全吗?

    go - context.WithValue : how to add several key-value pairs

    concurrency - Io 语言如何自动检测死锁?

    c++ - 如何修复 C++ 中的错误 "vector iterators in range are from different containers"?

    c++ - 从字符串中打印出 HTML 标签

    MySQL锁定重复键错误