muduo庫的隊列很簡單:
無界隊列
put --生產
take--消費
size--返回現在的產品數
產品存放在deque裏面
無界隊列可以一直生產put,所以不用等待隊列中有位置才生產,每生產一個產品就notify,只要通知一個消費者,不需要通知所有人
只有消費take時要判斷有無產品,所以只需要一個mutex鎖,一個條件變量notEmpty,消費者用來等待notEmpty有產品可以消費
#ifndef MUDUO_BASE_BLOCKINGQUEUE_H
#define MUDUO_BASE_BLOCKINGQUEUE_H
#include <muduo/base/Condition.h>
#include <muduo/base/Mutex.h>
#include <boost/noncopyable.hpp>
#include <deque>
#include <assert.h>
namespace muduo
{
template<typename T>
class BlockingQueue : boost::noncopyable
{
public:
explicit BlockingQueue()
:mutex_(),
notEmptyCond_(mutex_),
queue_()
{}
void put(const T& t)
{
{
MutexLockGuard lock(mutex_);
queue_.push_back(t);
}
notEmptyCond_.notify();//不需要notifyAll通知所有的,如果有阻塞,代表原先爲空,現在只生產了一個,也只要一個消費來就足夠了
}
T take()
{
MutexLockGuard lock(mutex_);
while(queue_.empty())
notEmptyCond_.wait();
assert(!queue_.empty());
T front=queue_.front();
queue_.pop_front();
return front;
}
size_t size() const
{
MutexLockGuard lock(mutex_);
return queue_.size();
}
private:
mutable MutexLock mutex_;
Condition notEmptyCond_;
std::deque<T> queue_;
};
}
#endif
有界隊列
// Use of this source code is governed by a BSD-style license
// that can be found in the License file.
//
// Author: Shuo Chen (chenshuo at chenshuo dot com)
#ifndef MUDUO_BASE_BOUNDEDBLOCKINGQUEUE_H
#define MUDUO_BASE_BOUNDEDBLOCKINGQUEUE_H
#include <muduo/base/Condition.h>
#include <muduo/base/Mutex.h>
#include <boost/circular_buffer.hpp>
#include <boost/noncopyable.hpp>
#include <assert.h>
namespace muduo
{
template<typename T>
class BoundedBlockingQueue : boost::noncopyable
{
public:
explicit BoundedBlockingQueue(int maxSize)
: mutex_(),
notEmpty_(mutex_),
notFull_(mutex_),
queue_(maxSize)
{
}
void put(const T& x)
{
MutexLockGuard lock(mutex_);
while (queue_.full())
{
notFull_.wait();
}
assert(!queue_.full());
queue_.push_back(x);
notEmpty_.notify(); // TODO: move outside of lock
}
T take()
{
MutexLockGuard lock(mutex_);
while (queue_.empty())
{
notEmpty_.wait();
}
assert(!queue_.empty());
T front(queue_.front());
queue_.pop_front();
notFull_.notify(); // TODO: move outside of lock
return front;
}
bool empty() const
{
MutexLockGuard lock(mutex_);
return queue_.empty();
}
bool full() const
{
MutexLockGuard lock(mutex_);
return queue_.full();
}
size_t size() const
{
MutexLockGuard lock(mutex_);
return queue_.size();
}
size_t capacity() const
{
MutexLockGuard lock(mutex_);
return queue_.capacity();
}
private:
mutable MutexLock mutex_;//一把鎖,兩個條件變量共用一把鎖
Condition notEmpty_;
Condition notFull_;
boost::circular_buffer<T> queue_;
};
}
#endif // MUDUO_BASE_BOUNDEDBLOCKINGQUEUE_H
參考:c++教程網