c++怎么实现一个阻塞队列_c++生产者消费者模型实现【多线程】

admin 百科 24
该文实现了基于C++标准库的线程安全阻塞队列模板类BlockingQueue,支持容量限制、阻塞入队/出队及超时尝试出队;配套生产者生成随机数、消费者取数处理,并通过多线程协同演示完整生产者-消费者模型。

c++怎么实现一个阻塞队列_c++生产者消费者模型实现【多线程】-第1张图片-佛山资讯网

(以下为纯 C++ 多线程阻塞队列 + 生产者消费者模型实现,基于标准库 <queue></queue><mutex></mutex><condition_variable></condition_variable><thread></thread>,无第三方依赖,可直接编译运行)

核心思路:用互斥锁保护共享队列,用条件变量让空队列时消费者等待、满队列时生产者等待。C++ 标准库的 std::condition_variable 天然支持“等待某个条件成立”,配合 wait()notify_one()/notify_all() 即可实现线程安全的阻塞行为。

1. 线程安全的阻塞队列模板类

支持任意类型 T,可设容量上限(可选),内部自动处理 wait/notify 逻辑:

#include <queue>
#include <mutex>
#include <condition_variable>
#include <chrono>

template<typename T>
class BlockingQueue {
private:
    std::queue<T> q;
    mutable std::mutex mtx;
    std::condition_variable not_empty;   // 消费者等待:队列非空
    std::condition_variable not_full;    // 生产者等待:队列未满(若限容)
    size_t max_size = 0;                 // 0 表示无容量限制

public:
    explicit BlockingQueue(size_t capacity = 0) : max_size(capacity) {}

    // 入队(阻塞直到有空间)
    void push(const T& item) {
        std::unique_lock<std::mutex> lock(mtx);
        if (max_size > 0) {
            not_full.wait(lock, [this] { return q.size() < max_size; });
        }
        q.push(item);
        not_empty.notify_one(); // 唤醒一个等待消费的线程
    }

    // 出队(阻塞直到有数据)
    T pop() {
        std::unique_lock<std::mutex> lock(mtx);
        not_empty.wait(lock, [this] { return !q.empty(); });
        T front = std::move(q.front());
        q.pop();
        if (max_size > 0) {
            not_full.notify_one(); // 可能腾出空间,唤醒一个等待生产的线程
        }
        return front;
    }

    // 尝试出队(带超时,返回 false 表示超时或为空)
    bool try_pop(T& item, int timeout_ms = 0) {
        std::unique_lock<std::mutex> lock(mtx);
        if (timeout_ms == 0) {
            not_empty.wait(lock, [this] { return !q.empty(); });
        } else {
            auto dur = std::chrono::milliseconds(timeout_ms);
            if (!not_empty.wait_for(lock, dur, [this] { return !q.empty(); })) {
                return false;
            }
        }
        item = std::move(q.front());
        q.pop();
        if (max_size > 0) not_full.notify_one();
        return true;
    }

    size_t size() const {
        std::lock_guard<std::mutex> lock(mtx);
        return q.size();
    }

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

登录后复制

2. 生产者与消费者函数(分离职责)

每个生产者/消费者都是独立函数,通过引用使用同一个队列,适合传给 std::thread

标签: ai c++ ios stream 标准库

发布评论 0条评论)

还木有评论哦,快来抢沙发吧~

趣科技 机圈观察员 茄考网 茄录网 海印网 雷鹃网 鹃朝网 互联网观察员 评测官
趣科技 机圈观察员 茄考网 茄录网 海印网 雷鹃网 鹃朝网 互联网观察员 评测官