线程安全队列通过std::mutex和std::condition_variable实现,确保多线程下push和pop操作的安全性与阻塞等待机制,适用于生产者-消费者模型,需注意死锁预防、条件变量正确使用及性能权衡。

在多线程编程中,多个线程同时访问共享资源容易引发数据竞争和不一致问题。队列作为常见的数据结构,在任务调度、生产者-消费者模型等场景中频繁使用,因此实现一个线程安全的队列至关重要。C++ 中可以通过互斥锁(std::mutex)结合条件变量(std::condition_variable)来实现一个高效且安全的线程安全队列。
线程安全队列的核心目标是保证在多线程环境下对队列的 push 和 pop 操作不会导致数据损坏,并支持阻塞等待机制,提高程序响应性。
主要组件包括:
以下是一个完整的线程安全队列模板实现:
立即学习“C++免费学习笔记(深入)”;
#include <queue>
#include <mutex>
#include <condition_variable>
#include <thread>
template<typename T>
class ThreadSafeQueue {
private:
std::queue<T> data_queue;
mutable std::mutex mtx;
std::condition_variable cv;
public:
ThreadSafeQueue() = default;
void push(T value) {
std::lock_guard<std::mutex> lock(mtx);
data_queue.push(std::move(value));
cv.notify_one(); // 通知一个等待的消费者
}
bool try_pop(T& value) {
std::lock_guard<std::mutex> lock(mtx);
if (data_queue.empty()) {
return false;
}
value = std::move(data_queue.front());
data_queue.pop();
return true;
}
void wait_and_pop(T& value) {
std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock, [this] { return !data_queue.empty(); });
value = std::move(data_queue.front());
data_queue.pop();
}
bool empty() const {
std::lock_guard<std::mutex> lock(mtx);
return data_queue.empty();
}
size_t size() const {
std::lock_guard<std::mutex> lock(mtx);
return data_queue.size();
}
};
这个队列可以安全地在多个生产者和消费者之间共享。例如:
ThreadSafeQueue<int> queue;
// 生产者线程
auto producer = [&]() {
for (int i = 0; i < 5; ++i) {
queue.push(i);
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
};
// 消费者线程
auto consumer = [&]() {
int value;
for (int i = 0; i < 5; ++i) {
queue.wait_and_pop(value);
std::cout << "Consumed: " << value << std::endl;
}
};
std::thread t1(producer);
std::thread t2(consumer);
t1.join();
t2.join();
注意点:
以上就是c++++怎么实现一个线程安全的队列_c++线程安全队列设计与实现方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号