LoginSignup
16
13

More than 5 years have passed since last update.

boost::threadとstd::queueを使ったblocking queueの実装

Posted at

中身が空っぽだったら待つだけのベーシックな並行キュー。
conditionを正しく使う為に毎回conditionの使い方ググるのが面倒くさいのでここに置いておく。

#ifndef BLOCKING_QUEUE_HPP_
#define BLOCKING_QUEUE_HPP_
#include <boost/thread.hpp>
#include <queue>

template <typename T>
class blocking_queue {
public:
  blocking_queue() {}
  void enqueue(const T& item) {
    {
      boost::mutex::scoped_lock lk(lk_);
      const bool was_empty = queue_.empty();
      queue_.push(item);
      if (was_empty) {
        empty_wait_.notify_all();  // notify_one() may be suitable?
      }
    }
  }

  T dequeue() {
    while (true) {
      boost::mutex::scoped_lock lk(lk_);
      if (queue_.empty()) {  // if empty
        empty_wait_.wait(lk);  // unlock
        //  relock
      }
      if (queue_.empty()) {
        continue;
      }

      T result = queue_.front();
      queue_.pop();
      return result;
    }
  }

  size_t size() const {
    boost::mutex::scoped_lock lk(lk_);
    return queue_.size();
  }

private:
  mutable boost::mutex lk_;
  mutable boost::condition_variable empty_wait_;
  std::queue<T> queue_;
};
#endif  // BLOCKING_QUEUE_HPP_

内部をもっとスケーラブルな構造にしたり、このデータ構造を複数使ってMulti Lane作るもよし。

16
13
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
13