1// excerpts from http://code.google.com/p/muduo/
2//
3// Use of this source code is governed by a BSD-style license
4// that can be found in the License file.
5//
6// Author: Shuo Chen (giantchen at gmail dot com)
7
8#ifndef MUDUO_BASE_BLOCKINGQUEUE_H
9#define MUDUO_BASE_BLOCKINGQUEUE_H
10
11#include "Condition.h"
12#include "Mutex.h"
13
14#include <boost/noncopyable.hpp>
15#include <deque>
16#include <assert.h>
17
18namespace muduo
19{
20
21template<typename T>
22class BlockingQueue : boost::noncopyable
23{
24 public:
25  BlockingQueue()
26    : mutex_(),
27      notEmpty_(mutex_),
28      queue_()
29  {
30  }
31
32  void put(const T& x)
33  {
34    MutexLockGuard lock(mutex_);
35    queue_.push_back(x);
36    notEmpty_.notify();
37  }
38
39  T take()
40  {
41    MutexLockGuard lock(mutex_);
42    // always use a while-loop, due to spurious wakeup
43    while (queue_.empty())
44    {
45      notEmpty_.wait();
46    }
47    assert(!queue_.empty());
48    T front(queue_.front());
49    queue_.pop_front();
50    return front;
51  }
52
53  size_t size() const
54  {
55    MutexLockGuard lock(mutex_);
56    return queue_.size();
57  }
58
59 private:
60  mutable MutexLock mutex_;
61  Condition         notEmpty_;
62  std::deque<T>     queue_;
63};
64
65}
66
67#endif  // MUDUO_BASE_BLOCKINGQUEUE_H
68