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


该文实现了基于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++生产者消费者模型实现【多线程】的详细内容,更多请关注其它相关文章!


# 并在  # 广州网站建设天维  # 烟草建设网站  # 商南短视频seo地址  # 顺德家政网站建设  # 网站推广渠道运营方案  # 武侯区网站推广建设优化  # 庆阳网站建设及推广  # 网站下线推广  # 零售怎么抖音推广优化营销  # 成安优化seo  # 中文网  # 相关文章  # ai  # 多个  # 边缘  # 都是  # 游戏开发  # 如何实现  # 随机数  # 多线程  # 标准库  # stream  # ios  # c++ 


相关栏目: 【 Google疑问12 】 【 Facebook疑问10 】 【 优化推广96088 】 【 技术知识133117 】 【 IDC资讯59369 】 【 网络运营7196 】 【 IT资讯61894 】


相关推荐: 一点万象签到领积分指南  《全民k歌》音乐怎么下载到本地2025  mysql如何管理数据库账户_mysql数据库账户管理技巧  Sublime怎么格式化HTML代码_Sublime前端代码美化插件使用指南  《顺丰同城骑士》查看我的技能方法  德邦物流在线查询系统 德邦快递货物运输追踪  太平年在哪个平台播出  Google Drive API服务器端访问指南:服务账户认证详解  HTML Canvas文本样式定制指南:解决外部字体加载与应用难题  b站网页版入口 哔哩哔哩官方网站直接进入  在Django中动态检查模型关联:一种灵活的解决方案  《伊瑟》凶影追缉库卢鲁boss攻略  《漫蛙manwa2》防走失网页版链接2025  汽水音乐网页端访问 汽水音乐官方网页直达  发博客与长微博技巧  《淘宝联盟》推广自己的店铺方法  CDR如何复制交互式填充色  冬季去寒冷地区旅游,以下哪种做法有助于缓解冻伤  Dagster资产间数据传递与用户配置管理教程  菜鸟驿站的取件码忘了怎么办 手机快速查询指南  C#解析来自网络的XML流数据 实时错误处理与重试机制  excel怎么制作考勤表 excel考勤模板与函数公式讲解  win11关机几秒又自己开机 Win11关机自动重启问题修复  《优志愿》修改手机号方法  《火影忍者:木叶高手》快速升级攻略  圆通快递官网入口查询单号 手机版官方查询入口  《搜书吧》阅读书籍方法  《虎扑》取消评分记录方法  c++类和对象到底是什么_c++面向对象编程基础  微博网页版访问入口 微博网页版网页端使用指南  抖音团长模式怎么做?团长模式是什么意思?  Win10如何关闭开机锁屏界面_Windows10跳过锁屏直接登录设置  Pandas中基于动态偏移量实现DataFrame列值位移的策略  b站怎么用微信登录_b站微信登录方法  win11怎么更改账户类型 Win11标准用户和管理员权限切换【教程】  PHP页面重载时变量值不重置的实现方法  word页码灰色不能用如何解决  《全民k歌》网页版最新登录入口一览  深入理解Python对象引用与链表属性赋值  处理含命名空间的XML文件 Power Query中的高级技巧  C++如何实现矩阵乘法_C++二维数组矩阵运算代码示例  CSS如何控制元素外边距_margin实现布局间隔  如何在mysql中设计餐饮点餐系统_mysql点餐系统项目实战  《暗黑破坏神4》国服回归送狂欢礼包 价值6916元  被称为海蜈蚣的海洋动物是  12306不能订票的时间段是固定的吗? | 节假日购票时间有无变化  《荔枝fm》导出文件教程  《猎聘》筛选猎头岗位方法  《小黑盒》删除历史浏览方法  抖音小程序怎么开通?小程序开通条件是什么? 

 2025-12-20

了解您产品搜索量及市场趋势,制定营销计划

同行竞争及网站分析保障您的广告效果

点击免费数据支持

提交您的需求,1小时内享受我们的专业解答。

运城市盐湖区信雨科技有限公司


运城市盐湖区信雨科技有限公司

运城市盐湖区信雨科技有限公司是一家深耕海外推广领域十年的专业服务商,作为谷歌推广与Facebook广告全球合作伙伴,聚焦外贸企业出海痛点,以数字化营销为核心,提供一站式海外营销解决方案。公司凭借十年行业沉淀与平台官方资源加持,打破传统外贸获客壁垒,助力企业高效开拓全球市场,成为中小企业出海的可靠合作伙伴。

 8156699

 13765294890

 8156699@qq.com

Notice

We and selected third parties use cookies or similar technologies for technical purposes and, with your consent, for other purposes as specified in the cookie policy.
You can consent to the use of such technologies by closing this notice, by interacting with any link or button outside of this notice or by continuing to browse otherwise.