阻塞队列就是多线程线程安全的队列,在多线程场景下经常用到,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) = delete;
BlockingQueue<T>& operator=(const BlockingQueue<T>& other) =

本文介绍了如何在C++中实现阻塞队列,这是一种用于多线程环境的安全队列。标准库虽未提供,但在Boost中有支持。文章详细阐述了使用环形队列和互斥锁实现阻塞队列的设计思路,并展示了生成者消费者模型的示例,其中生成者线程不断插入随机数,消费者线程进行消费。完整的代码可以在作者的GitHub仓库找到。
最低0.47元/天 解锁文章
76

被折叠的 条评论
为什么被折叠?



