生产者-消费者模式是一个十分经典的多线程并发协做的模式,弄懂生产者-消费者问题可以让咱们对并发编程的理解加深。所谓生产者-消费者问题,实际上主要是包含了两类线程,一种是生产者线程用于生产数据,另外一种是消费者线程用于消费数据,为了解耦生产者和消费者的关系,一般会采用共享的数据区域,就像是一个仓库,生产者生产数据以后直接放置在共享数据区中,并不须要关心消费者的行为;而消费者只须要从共享数据区中去获取数据,就再也不须要关心生产者的行为。可是,这个共享数据区域中应该具有这样的线程间并发协做的功能:ios
可是本篇文章不是说的多线程问题,而是为了完成一个功能,设置一个大小固定的工厂,生产者不断的往仓库里面生产数据,消费者从仓库里面消费数据,功能相似于一个队列,每一次生产者生产数据放到队尾,消费者从头部不断消费数据,如此循环处理相关业务。编程
下面是一个泛型的工厂类,能够不断的生产数据,消费者不断的消费数据。多线程
// // Created by muxuan on 2019/6/18. // #include <iostream> #include <vector> using namespace std; #ifndef LNRT_FACTORY_H #define LNRT_FACTORY_H template<typename T> class Factory { private: vector<T> _factory; int _size = 5; bool logEnable = false; public: void produce(T item); T consume(); void clear(); void configure(int cap, bool log = false); }; template<typename T> void Factory<T>::configure(int cap, bool log) { this->_size = cap; this->logEnable = log; } template<typename T> void Factory<T>::produce(T item) { if (this->_factory.size() < this->_size) { this->_factory.push_back(item); if (logEnable) cout << "produce product " << item << endl; return; } if (logEnable) cout << "consume product " << this->consume() << endl; this->_factory[this->_size - 1] = item; if (logEnable) cout << "produce product " << item << endl; } template<typename T> T Factory<T>::consume() { T item = this->_factory[0]; for (int i = 1; i < this->_size; i++) this->_factory[i - 1] = this->_factory[i]; return item; } template<typename T> void Factory<T>::clear() { for (int i = 0; i < this->_size; i++) if (logEnable) cout << "consume product " << this->consume() << endl; } #endif //LNRT_FACTORY_H
Factory<int> factory; factory.configure(5,true); for (int i = 0; i < 10; ++i) { factory.produce(i); } factory.clear();
该类能够很方便的实现分组问题,好比处理视频序列时候将第i帧到第j帧数据做为一个分组处理任务,能够用下面的方法来实现。并发