线程安全队列通过互斥锁和条件变量实现,确保多线程下数据同步;push插入元素并通知等待线程,wait_and_pop阻塞等待非空,try_pop提供非阻塞尝试,empty和size返回队列状态,适用于生产者-消费者模型。

在C++多线程编程中,线程安全的队列是常见的需求,比如生产者-消费者模型。要实现一个线程安全的队列,关键在于保护共享数据不被多个线程同时访问或修改。通常的做法是结合标准库中的 std::queue、std::mutex 和 std::condition_variable 来实现线程同步。
实现线程安全队列的核心目标是:
#include <iostream>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <vector>
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();
}
};
void producer(ThreadSafeQueue<int>& queue) {
for (int i = 0; i < 5; ++i) {
queue.push(i);
std::cout << "Produced: " << i << "\n";
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
void consumer(ThreadSafeQueue<int>& queue) {
for (int i = 0; i < 5; ++i) {
int value;
queue.wait_and_pop(value);
std::cout << "Consumed: " << value << "\n";
}
}
int main() {
ThreadSafeQueue<int> queue;
std::vector<std::thread> threads;
threads.emplace_back(producer, std::ref(queue));
threads.emplace_back(consumer, std::ref(queue));
for (auto& t : threads) {
t.join();
}
return 0;
}
push() 操作加锁后插入元素,并调用 notify_one() 唤醒一个等待的消费者。
wait_and_pop() 使用 unique_lock 配合 condition_variable 实现阻塞等待,避免忙等。
立即学习“C++免费学习笔记(深入)”;
try_pop() 提供非阻塞版本,适合某些需要轮询但不希望卡住的场景。
所有公共方法都对 mutex 加锁,确保任意时刻只有一个线程能操作队列。
基本上就这些。这个实现适用于大多数常规多线程场景,性能良好且易于理解。如果需要更高性能,可考虑无锁队列(lock-free queue),但复杂度会显著上升。
以上就是C++怎么实现一个线程安全的队列_C++多线程安全队列实现思路与示例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号