1 阻塞队列的定义
首先阻塞队列肯定是一个队列,是一种先进先出的数据结果,与一般的数据结构相比,多了阻塞两个字,对应的与普通队列不同的点如下:
当队列空时,从队列中取出元素会阻塞(先等着,直到队列中有元素为止)
当队列满时,往队列中增加元素会阻塞(队列有容量限制,不能无节制的往队列中增加元素)
阻塞队列常用来实现生产者消费者模型。
2 阻塞队列的C++实现
分为:无界阻塞队列和有界阻塞队列
区别:无界阻塞队列,push操作的时候,不阻塞
有界阻塞队列,push操作的时候阻塞。
下面代码为无界阻塞队列示例,有界阻塞队列得用两个条件变量,也就是相当于生产者消费者这种关系。
#ifndef BLOCKQUEUE_H_
#define BLOCKQUEUE_H_
#include <queue>
#include <mutex>
#include <condition_variable>
#include <cassert>
template <typename T>
class BlockQueue
{
public:
BlockQueue()
{
isClose = false;
}
~BlockQueue()
{
isClose = true;
cond_.notify_all();
}
void Push(T &&value) //右值引用:临时变量时避免拷贝
{
std::unique_lock<std::mutex> lock(mutex_);
queue_.push(value);
cond_.notify_one();
}
void Push(const T &value) //左值引用:长期存在的变量避免拷贝
{
std::unique_lock<std::mutex> lock(mutex_);
queue_.push(value);
cond_.notify_one();
}
bool Take(T& item) //取出头节点并删除头节点
{
std::unique_lock<std::mutex> lock(mutex_);
while (queue_.size() == 0) {
cond_.wait(lock);
if (isClose) {
return false;
}
}
item = std::move(queue_.front());
queue_.pop();
return true;
}
bool Front(T& item) //取出头节点
{
std::unique_lock<std::mutex> lock(mutex_);
while (queue_.size() == 0) {
cond_.wait(lock);
if (isClose) {
return false;
}
}
item = std::move(queue_.front());
return true;
}
void Pop() //删除头节点
{
std::unique_lock<std::mutex> lock(mutex_);
while (queue_.size() == 0) {
cond_.wait(lock);
if (isClose) {
return false;
}
}
queue_.pop();
return true;
}
size_t Size()
{
std::unique_lock<std::mutex> lock(mutex_);
return queue_.size();
}
private:
std::queue<T> queue_;
bool isClose;
std::mutex mutex_;
std::condition_variable cond_;
};
#endif