C++线程安全队列

在 C++ 中,多线程队列(queue)的实现通常需要考虑线程安全问题,特别是在多个线程需要同时对队列进行操作时。C++ 标准库中的 std::queue 并不是线程安全的,因此我们需要引入额外的机制来确保线程安全。常用的方法是使用互斥锁(mutex)和条件变量(condition variable)。

下面是一个使用 std::queue 实现线程安全队列的示例:

cpp 复制代码
#include <iostream>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>

template <typename T>
class ThreadSafeQueue {
private:
    std::queue<T> queue;
    std::mutex mtx;
    std::condition_variable cv;

public:
    void push(T value) {
        std::lock_guard<std::mutex> lock(mtx);
        queue.push(value);
        cv.notify_one(); // 通知一个等待线程
    }

    T pop() {
        std::unique_lock<std::mutex> lock(mtx);
        cv.wait(lock, [this]() { return !queue.empty(); }); // 等待队列非空
        T value = queue.front();
        queue.pop();
        return value;
    }

    bool empty() {
        std::lock_guard<std::mutex> lock(mtx);
        return queue.empty();
    }
};

void producer(ThreadSafeQueue<int>& tsq) {
    for (int i = 0; i < 10; ++i) {
        std::cout << "Producing: " << i << std::endl;
        tsq.push(i);
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }
}

void consumer(ThreadSafeQueue<int>& tsq) {
    for (int i = 0; i < 10; ++i) {
        int value = tsq.pop();
        std::cout << "Consuming: " << value << std::endl;
    }
}

int main() {
    ThreadSafeQueue<int> tsq;

    std::thread prod_thread(producer, std::ref(tsq));
    std::thread cons_thread(consumer, std::ref(tsq));

    prod_thread.join();
    cons_thread.join();

    return 0;
}

在这个示例中,我们定义了一个模板类 ThreadSafeQueue,它使用 std::queue 作为基础容器,并通过 std::mutexstd::condition_variable 实现了线程安全的 pushpop 操作。

  • push 方法向队列中添加元素,并通知一个等待的线程。
  • pop 方法从队列中取出元素,如果队列为空,则等待直到有元素被添加进来。
  • empty 方法检查队列是否为空。

main 函数中,我们创建了两个线程:一个生产者线程(producer),它负责向队列中添加元素;一个消费者线程(consumer),它负责从队列中取出元素。通过互斥锁和条件变量,我们确保了这些操作的线程安全性。

相关推荐
汉克老师36 分钟前
CSP-J 2026 初赛试题解析(第一部分:选择题(8-15))精讲
c++·csp-j·小学生·学c++编程
wabs6661 小时前
关于二叉树【力扣572.另一棵树的子树的思考】
数据结构·c++·算法·leetcode·二叉树
风合星语2 小时前
2026 ROS 2 Lyrical C++ 入门(五):Action 实战——任务反馈、取消与超时处理
c++·机器人·ros2·异步编程·lyrical
91刘仁德3 小时前
C++ 继承和多态 设计模式
c语言·c++·笔记
库玛西3 小时前
哈夫曼树与前缀编码:数据压缩的贪心核心
c语言·c++·笔记·考研
别动我齐刘海4 小时前
ROS2 Jazzy + C++ 实战路线——进阶学习3
c++·人工智能·vscode·python·算法·机器学习·机器人
0+1114 小时前
算法 --滑动窗口
c++·算法·leetcode
stolentime4 小时前
(有原题)CSP-S2026第一轮试题(附答案解析、markdown源码)
c++·csp
m0_734571764 小时前
深入理解C++ RAII
开发语言·c++
hetao17338374 小时前
2026-09-18 hetao1733837 的刷题记录
c++·算法