阻塞队列就是多线程线程安全的队列,在多线程场景下经常用到,c++ 标准库里面没有提供阻塞队列,boost 中有提供,生成环境下可以使用
blocking queue 实现
主要设计思路:
- 使用
std::vector
实现一个环形队列,使用两个指针 start 和 end 来标识起止位置,push 的时候在 end 处插入,pop 的时候直接 start 指针往后移即可 - 使用
std::condition_variable
实现同步,push 的时候需要满足_not_full
条件,push 完成发送_not_empty
通知,pop 的时候需要满足_not_empty
条件,pop 完成发送_not_full
通知
template <typename T>
class BlockingQueue {
std::mutex _mutex;
std::condition_variable _not_full;
std::condition_variable _not_empty;
int _start;
int _end;
int _capacity;
std::vector<T> _vt;
public:
BlockingQueue(const BlockingQueue<T>& other)