C++设计模式-生产者消费者模式

打印 上一主题 下一主题

主题 561|帖子 561|积分 1683

运行在VS2022,x86,Debug下。
32. 生产者消费者模式



  • 解耦生产者和消费者之间的关系,即生产者和消费者只依赖缓冲区,而不相互依赖。
  • 应用:多线程并发编程,可以办理生产者和消费者之间的同步问题。
  • 实现

    • 生产者:负责产生数据的模块。
    • 消费者:负责处理数据的模块。
    • 中介:缓冲区。

  • 代码如下。
    lambda表达式在condition_variable::wait()中充当断言。
  1. #include <iostream>
  2. #include <thread>
  3. #include <mutex>
  4. #include <condition_variable>
  5. #include <queue>
  6. #include <vector>
  7. using namespace std;
  8. const int BUFFER_SIZE = 10;  //缓冲区大小
  9. queue<int> buffer;           //缓冲区, 用于存放数据
  10. mutex mtx;                   //互斥量,用于保护共享资源
  11. condition_variable prod_cv; // 生产者条件变量,用于线程间的同步
  12. condition_variable cons_cv; // 消费者条件变量
  13. //生产者
  14. void producer()
  15. {
  16.     for (int i = 0; i < 20; i++)   //循环生产20个数据
  17.     {
  18.         unique_lock<mutex> lock(mtx);    //独占锁,确保同一时刻只有一个线程访问临界区
  19.         prod_cv.wait(lock, [] { return buffer.size() < BUFFER_SIZE; });    //等待条件满足,即缓冲区不满
  20.         buffer.push(i);
  21.         cout << "Producer ID:" << this_thread::get_id() << " Produced: " << i << std::endl;
  22.         lock.unlock();            //解锁互斥量
  23.         cons_cv.notify_all();     //通知消费者
  24.         this_thread::sleep_for(std::chrono::milliseconds(500)); //睡眠, 模拟生产过程
  25.     }
  26. }
  27. //消费者
  28. void consumer()
  29. {
  30.     for (int i = 0; i < 20; i++)   //循环消费20个数据
  31.     {
  32.         unique_lock<std::mutex> lock(mtx);
  33.         cons_cv.wait(lock, [] { return !buffer.empty(); });  //等待条件满足,即缓冲区不为空
  34.         cout << "Consumer ID:" << this_thread::get_id() << " Consumed: " << buffer.front() << endl;
  35.         buffer.pop();
  36.         lock.unlock();
  37.         prod_cv.notify_all();  //通知生产者
  38.         this_thread::sleep_for(std::chrono::milliseconds(800));
  39.     }
  40. }
  41. int main()
  42. {
  43.     const int num_producers = 2;  //生产者数量
  44.     const int num_consumers = 2;  //消费者数量
  45.     vector<thread> producer_threads;
  46.     vector<thread> consumer_threads;
  47.     for (int i = 0; i < num_producers; i++)   //创建生产者线程
  48.         producer_threads.emplace_back(producer);
  49.     for (int i = 0; i < num_consumers; i++)  //创建消费者线程
  50.         consumer_threads.emplace_back(consumer);
  51.     for (auto&& thread : producer_threads)  //等待所有生产者线程结束
  52.         thread.join();
  53.     for (auto&& thread : consumer_threads)  //等待所有消费者线程结束
  54.         thread.join();
  55.     return 0;   
  56. }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

正序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

反转基因福娃

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表