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;
}
相关推荐
csbysj20204 分钟前
React 表单与事件
开发语言
初圣魔门首席弟子7 分钟前
c++ bug 函数定义和声明不一致导致出bug
开发语言·c++·bug
IT小农工26 分钟前
Word 为每一页设置不同页边距(VBA 宏)
开发语言·c#·word
sali-tec1 小时前
C# 基于halcon的视觉工作流-章42-手动识别文本
开发语言·人工智能·算法·计算机视觉·c#·ocr
csbysj20201 小时前
中介者模式
开发语言
hsjkdhs2 小时前
C++之类的继承与派生
开发语言·c++
lly2024062 小时前
HTML 元素:构建网页的基础
开发语言
低调小一2 小时前
LRU缓存科普与实现(Kotlin 与 Swift)
开发语言·缓存·kotlin
爱好学习的青年人2 小时前
一文详解Go语言字符串
开发语言·后端·golang
浅川.253 小时前
xtuoj string
开发语言·c++·算法