C++ 并发专题 - 实现一个线程安全的队列

一:概述

本文利用 C++ 标准库中的多线程、条件变量、互斥锁等工具来实现一个线程安全的队列,并且使用多个线程来向队列中添加和获取数据。

二:实现过程:

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

template <typename T>
class ThreadSafeQueue {
public:
    // 向队列中添加元素
    void push(const T& value) {
        std::lock_guard<std::mutex> lock(mutex_);
        queue_.push(value);
        cond_var_.notify_one();  // 通知一个等待的线程
    }

    // 从队列中取出元素,如果队列为空,阻塞等待
    T pop() {
        std::unique_lock<std::mutex> lock(mutex_);
        cond_var_.wait(lock, [this] { return !queue_.empty(); });  // 等待直到队列非空
        T value = queue_.front();
        queue_.pop();
        return value;
    }

    // 判断队列是否为空
    bool empty() const {
        std::lock_guard<std::mutex> lock(mutex_);
        return queue_.empty();
    }

private:
    mutable std::mutex mutex_;            // 互斥锁,保护队列
    std::queue<T> queue_;                 // 基础队列
    std::condition_variable cond_var_;   // 条件变量,用于队列为空时的等待
};

// 示例:使用线程安全队列
void producer(ThreadSafeQueue<int>& queue, int numItems) {
    for (int i = 0; i < numItems; ++i) {
        queue.push(i);
        std::cout << "Produced: " << i << std::endl;
    }
}

void consumer(ThreadSafeQueue<int>& queue, int numItems) {
    for (int i = 0; i < numItems; ++i) {
        int item = queue.pop();
        std::cout << "Consumed: " << item << std::endl;
    }
}

int main() {
    ThreadSafeQueue<int> queue;

    const int numItems = 10;
    const int numProducers = 2;
    const int numConsumers = 2;

    std::vector<std::thread> threads;

    // 启动生产者线程
    for (int i = 0; i < numProducers; ++i) {
        threads.push_back(std::thread(producer, std::ref(queue), numItems / numProducers));
    }

    // 启动消费者线程
    for (int i = 0; i < numConsumers; ++i) {
        threads.push_back(std::thread(consumer, std::ref(queue), numItems / numConsumers));
    }

    // 等待所有线程完成
    for (auto& thr : threads) {
        thr.join();
    }

    return 0;
}
相关推荐
2601_966949656 小时前
如何根据研究的起止时间截取分钟级行情?Python 实战与 QuantDash 数据处理指南
开发语言·python·pandas·量化交易·1024程序员节·股票数据·quantdash
晨曦中的暮雨8 小时前
限流算法——固定窗口、滑动窗口、漏桶、令牌桶
java·开发语言·算法
喵了几个咪8 小时前
GoWind CMS 拆解:在 Go 里给 TipTap 搭一套 Yjs 协同后端
开发语言·后端·golang
程序员清风8 小时前
数据处理脚本工程化:日志、配置、命令行与测试
服务器·开发语言·数据库
2601_9628857210 小时前
如何用 Python 把 K 线重采样成任意周期?
开发语言·python
Wang's Blog11 小时前
Java 项目实战: 交友项目 - 圈子功能实现:总结
java·开发语言·交友
下一站春风里11 小时前
位运算完整学习笔记:按位与(&)+ 异或(^)
开发语言·c++·算法
天外飞雨道沧桑12 小时前
我在浏览器里练了一个 792 参数的大模型,它学会了补全 JavaScript
开发语言·javascript·ai·ecmascript·ai编程
hhhjhl12 小时前
Yup 跨端三方库仓颉适配全流程
java·开发语言
运维行者_13 小时前
网络监控工具怎么选?从设备监控到智能运维的能力清单
运维·服务器·开发语言·网络·人工智能·支持向量机·php