答案是使用互斥锁、条件变量和队列实现线程安全的阻塞队列,通过加锁和条件等待确保push和pop操作在多线程下的正确性,支持阻塞与唤醒机制。

在C++中实现一个线程安全的阻塞队列,核心是结合互斥锁(std::mutex)、条件变量(std::condition_variable)和一个底层容器(如 std::queue)。阻塞队列的特点是:当队列为空时,出队操作会阻塞;当队列满时(如果有容量限制),入队操作也会阻塞。
阻塞队列需要满足多线程环境下安全地进行 push 和 pop 操作。主要依赖以下机制:
两个核心成员函数是 push 和 pop,它们都需要加锁,并在特定条件下等待。
push(value) 操作流程:
立即学习“C++免费学习笔记(深入)”;
pop() -> value 操作流程:
下面是一个简单的线程安全阻塞队列实现:
#include <queue>
#include <mutex>
#include <condition_variable>
#include <thread>
template <typename T>
class BlockingQueue {
private:
std::queue<T> queue_;
std::mutex mtx_;
std::condition_variable not_empty_;
std::condition_variable not_full_;
size_t max_size_;
public:
explicit BlockingQueue(size_t max_size = SIZE_MAX) : max_size_(max_size) {}
void push(const T& item) {
std::unique_lock<std::mutex> lock(mtx_);
not_full_.wait(lock, [this] { return queue_.size() < max_size_; });
queue_.push(item);
not_empty_.notify_one();
}
T pop() {
std::unique_lock<std::mutex> lock(mtx_);
not_empty_.wait(lock, [this] { return !queue_.empty(); });
T item = std::move(queue_.front());
queue_.pop();
not_full_.notify_one();
return item;
}
bool empty() const {
std::lock_guard<std::mutex> lock(mtx_);
return queue_.empty();
}
size_t size() const {
std::lock_guard<std::mutex> lock(mtx_);
return queue_.size();
}
};
使用示例:
BlockingQueue<int> bq(5);
std::thread producer([&]() {
for (int i = 0; i < 10; ++i) {
bq.push(i);
std::cout << "Produced: " << i << "\n";
}
});
std::thread consumer([&]() {
for (int i = 0; i < 10; ++i) {
int val = bq.pop();
std::cout << "Consumed: " << val << "\n";
}
});
producer.join();
consumer.join();
实际使用中还需考虑一些细节:
以上就是c++++中如何实现一个阻塞队列_c++线程安全阻塞队列的设计思路的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号