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_BOUNDEDBLOCKINGQUEUE_H
9#define MUDUO_BASE_BOUNDEDBLOCKINGQUEUE_H
10
11#include "Condition.h"
12#include "Mutex.h"
13
14#include <boost/circular_buffer.hpp>
15#include <boost/noncopyable.hpp>
16#include <assert.h>
17
18namespace muduo
19{
20
21template<typename T>
22class BoundedBlockingQueue : boost::noncopyable
23{
24 public:
25  explicit BoundedBlockingQueue(int maxSize)
26    : mutex_(),
27      notEmpty_(mutex_),
28      notFull_(mutex_),
29      queue_(maxSize)
30  {
31  }
32
33  void put(const T& x)
34  {
35    MutexLockGuard lock(mutex_);
36    while (queue_.full())
37    {
38      notFull_.wait();
39    }
40    assert(!queue_.full());
41    queue_.push_back(x);
42    notEmpty_.notify(); // TODO: move outside of lock
43  }
44
45  T take()
46  {
47    MutexLockGuard lock(mutex_);
48    while (queue_.empty())
49    {
50      notEmpty_.wait();
51    }
52    assert(!queue_.empty());
53    T front(queue_.front());
54    queue_.pop_front();
55    notFull_.notify(); // TODO: move outside of lock
56    return front;
57  }
58
59  bool empty() const
60  {
61    MutexLockGuard lock(mutex_);
62    return queue_.empty();
63  }
64
65  bool full() const
66  {
67    MutexLockGuard lock(mutex_);
68    return queue_.full();
69  }
70
71  size_t size() const
72  {
73    MutexLockGuard lock(mutex_);
74    return queue_.size();
75  }
76
77  size_t capacity() const
78  {
79    MutexLockGuard lock(mutex_);
80    return queue_.capacity();
81  }
82
83 private:
84  mutable MutexLock          mutex_;
85  Condition                  notEmpty_;
86  Condition                  notFull_;
87  boost::circular_buffer<T>  queue_;
88};
89
90}
91
92#endif  // MUDUO_BASE_BOUNDEDBLOCKINGQUEUE_H
93