中身が空っぽだったら待つだけのベーシックな並行キュー。
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作るもよし。