源码可在https://github.com/learnmoreonce/SLAM 下载
文件:common/blocking_queue.h
#ifndef CARTOGRAPHER_COMMON_BLOCKING_QUEUE_H_
#define CARTOGRAPHER_COMMON_BLOCKING_QUEUE_H_
#include <cstddef>
#include <deque>
#include <memory>
#include "cartographer/common/mutex.h"
#include "cartographer/common/port.h"
#include "cartographer/common/time.h"
#include "glog/logging.h"
/*
* BlockingQueue是线程安全的阻塞队列,(生产者消费者模式)
* 不可拷贝不可赋值
* 构造函数初始化队列大小,kInfiniteQueueSize=0默认不限制容量。queue_size限制容量:通过条件变量做到.
* Push()添加元素,容量不够时,阻塞等待
* Pop()删除元素,没有元素时,阻塞等待
* Peek()返回下一个应该弹出的元素
* PushWithTimeout(),添加元素,若超时则返回false
* PopWithTimeout(),删除元素,若超时则返回false
*
* */
namespace cartographer {
namespace common {
// A thread-safe blocking queue that is useful for producer/consumer patterns.
// 'T' must be movable.
template <typename T>
class BlockingQueue {
public:
static constexpr size_t kInfiniteQueueSize = 0;
// Constructs a blocking queue with infinite queue size.
BlockingQueue() : BlockingQueue(kInfiniteQueueSize) {} //默认不限制容量
BlockingQueue(const BlockingQueue&) = delete;
BlockingQueue& operator=(const BlockingQueue&) = delete;
// Constructs a blocking queue with a size of 'queue_size'.限制容量
explicit BlockingQueue(const size_t queue_size) : queue_size_(queue_size) {}
// Pushes a value onto the queue. Blocks if the queue is full.
void Push(T t) {
MutexLocker lock(&mutex_);//加锁
lock.Await([this]() REQUIRES(mutex_) { return QueueNotFullCondition(); });//队列未满才能push
deque_.push_back(std::move(t));