首页 > 后端开发 > C++ > 正文

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

穿越時空
发布: 2025-12-20 15:49:02
原创
268人浏览过
该文实现了基于C++标准库的线程安全阻塞队列模板类BlockingQueue,支持容量限制、阻塞入队/出队及超时尝试出队;配套生产者生成随机数、消费者取数处理,并通过多线程协同演示完整生产者-消费者模型。

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

(以下为纯 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

Prisma
Prisma

Prisma是一款照片编辑工具,用户可以轻松地将照片转换成数字艺术。

Prisma 92
查看详情 Prisma

立即学习C++免费学习笔记(深入)”;

#include <iostream>
#include <thread>
#include <vector>
#include <random>

// 生产者:生成随机数并入队
void producer(BlockingQueue<int>& bq, int id, int count) {
    std::mt19937 gen(id);
    std::uniform_int_distribution<int> dist(1, 100);
    for (int i = 0; i < count; ++i) {
        int val = dist(gen);
        bq.push(val);
        std::cout << "[P" << id << "] pushed " << val << "\n";
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }
}

// 消费者:取数、打印、简单处理
void consumer(BlockingQueue<int>& bq, int id, int total) {
    for (int i = 0; i < total; ++i) {
        int val = bq.pop(); // 阻塞等待
        std::cout << "  [C" << id << "] popped " << val << "\n";
        std::this_thread::sleep_for(std::chrono::milliseconds(150));
    }
}
登录后复制

3. 主函数:启动多线程并协同运行

注意:需确保生产总数 ≥ 消费总数,否则消费者会永久阻塞(实际项目中建议加退出信号或使用 `try_pop` + 超时 + 中断机制):

int main() {
    BlockingQueue<int> bq(10); // 容量为 10 的有界队列

    const int num_producers = 2;
    const int num_consumers = 3;
    const int items_per_producer = 5;

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

    // 启动生产者
    for (int i = 0; i < num_producers; ++i) {
        threads.emplace_back(producer, std::ref(bq), i, items_per_producer);
    }

    // 启动消费者(总消费数 = 总生产数)
    int total_items = num_producers * items_per_producer;
    for (int i = 0; i < num_consumers; ++i) {
        int each = total_items / num_consumers;
        int rest = (i == 0) ? total_items % num_consumers : 0;
        threads.emplace_back(consumer, std::ref(bq), i, each + rest);
    }

    // 等待所有线程结束
    for (auto& t : threads) {
        if (t.joinable()) t.join();
    }

    std::cout << "All done.\n";
    return 0;
}
登录后复制

4. 关键细节提醒

  • 始终用 std::unique_lock 配合 wait:它允许在等待期间临时释放锁,并在唤醒后自动重新加锁;普通 lock_guard 不支持
  • 条件检查必须用 lambda(谓词重载):避免虚假唤醒(spurious wakeup),不要只用 wait(lock) 后手动判断
  • notify_one() 通常够用:除非多个线程等待同一条件且需全部响应(如广播终止信号),否则用 notify_one() 更高效
  • 移动语义优化:pop 中用 std::move(q.front()) 避免不必要的拷贝(尤其对大对象)
  • 异常安全:所有 RAII 锁(unique_lock / lock_guard)保证异常时自动解锁

基本上就这些。不复杂但容易忽略条件变量的谓词写法和锁的搭配——写对了,就是教科书级的线程安全阻塞队列。

以上就是c++++怎么实现一个阻塞队列_c++生产者消费者模型实现【多线程】的详细内容,更多请关注php中文网其它相关文章!

c++速学教程(入门到精通)
c++速学教程(入门到精通)

c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号