template <typename T>
class BoundedBlockingQueue {
public:
explicit BoundedBlockingQueue(int maxSize) : ringbuffer(maxSize) {
}
void put(const T& x) {
std::unique_lock<std::mutex> lock(mutex_);
notFull_.wait(lock, [&] { return !ringbuffer.full(); });
ringbuffer.push_back(x);
notEmpty_.notify_one();
}
void put(T&& x) {
std::unique_lock<std::mutex> lock(mutex_);
notFull_.wait(lock, [&] { return !ringbuffer.full(); });
ringbuffer.push_back(x);
notEmpty_.notify_one();
}
T take() {
std::unique_lock<std::mutex> lock(mutex_);
notEmpty_.wait(lock, [&] { return !ringbuffer.empty(); });
assert(!ringbuffer.empty());
T front(ringbuffer.front());
ringbuffer.pop_front();
notFull_.notify_one();
return front;
}
bool empty() const {
std::lock_guard<std::mutex> lock(mutex_);
[C++11] 线程安全的BoundedBlockingQueue
最新推荐文章于 2024-11-17 23:14:06 发布
本文介绍了如何使用C++11标准库中的特性,如std::mutex和std::condition_variable,来实现一个线程安全的、具有固定容量的BoundedBlockingQueue。内容涵盖队列的基本操作,如插入和删除元素,以及如何在满或空的情况下进行线程同步。

最低0.47元/天 解锁文章
958

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



