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-06-28 13:55:11 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)