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