C++11实现简单生产者消费者模式

本文介绍了一个基于C++11的简单生产者-消费者模式实现。该模式利用了C++11提供的多线程、互斥量及条件变量等功能,实现了生产者按1秒间隔向队列中添加数值,而消费者则按2秒间隔从队列中读取这些数值。
当前C++11已经实现了多线程、互斥量、条件变量等异步处理函数,并且提供了诸如sleep之类的时间函数,所以后面使用C++开发这一块的时候完全可以实现跨平台,无需在windows下写一套然后又在linux下写一套了。
    本文用C++11实现了一个简单的生产者-消费者模式,生产者每1S将一个数值放到双向队列中,消费者每2S从双向队列中取出数据。
[cpp]  view plain  copy
  1. #include "stdafx.h"  
  2. #include <thread>  
  3. #include <mutex>  
  4. #include <deque>  
  5. #include <vector>  
  6. #include <condition_variable>  
  7.   
  8. class CThreadDemo  
  9. {  
  10. private:  
  11.     std::deque<int> m_data;  
  12.     std::mutex m_mtx; // 全局互斥锁.  
  13.     std::condition_variable m_cv; // 全局条件变量.  
  14.     int       m_nGen;  
  15.   
  16. private:  
  17.     void ProductThread(){  
  18.         while (true){  
  19.             std::unique_lock <std::mutex> lck(m_mtx);  
  20.             m_nGen = ++m_nGen % 1000;  
  21.             printf("product %d\n", m_nGen);  
  22.             m_data.push_back(m_nGen);  
  23.             lck.unlock();  
  24.             m_cv.notify_all();  
  25.   
  26.             /* 等待1S */  
  27.             std::chrono::milliseconds dura(1000);  
  28.             std::this_thread::sleep_for(dura);  
  29.         }  
  30.     }  
  31.   
  32.     void ConsumeThread(){  
  33.         while (true){  
  34.             std::unique_lock <std::mutex> lck(m_mtx);  
  35.             while (m_data.empty()){  
  36.                 m_cv.wait(lck);  
  37.             }  
  38.             int nData = m_data.front();  
  39.             m_data.pop_front();  
  40.             printf("consume %d\n", nData);  
  41.             lck.unlock();  
  42.               
  43.             /* 等待2S */  
  44.             std::chrono::milliseconds dura(2000);  
  45.             std::this_thread::sleep_for(dura);  
  46.         }  
  47.     }  
  48. public:  
  49.     CThreadDemo(){  
  50.         m_data.clear();  
  51.         m_nGen = 0;  
  52.     }  
  53.   
  54.     void Start(){  
  55.         std::vector<std::thread> threads;  
  56.         threads.clear();  
  57.         for (int i = 0; i < 5; i++){/* 生产者线程 */  
  58.             threads.push_back(std::thread(&CThreadDemo::ProductThread, this));  
  59.         }  
  60.         for (int i = 5; i < 10; i++){/* 消费者线程 */  
  61.             threads.push_back(std::thread(&CThreadDemo::ConsumeThread, this));  
  62.         }  
  63.         for (auto& t : threads){/* 等待所有线程的退出 */  
  64.             t.join();  
  65.         }  
  66.     }  
  67. };  
  68.   
  69.   
  70. int _tmain(int argc, _TCHAR* argv[])  
  71. {  
  72.     CThreadDemo test;  
  73.     test.Start();  
  74.     return 0;  
  75. }  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值