C++实现生产者和消费者

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

C++实现⽣产者和消费者
传统的⽣产者消费者模型
⽣产者-消费者模式是⼀个⼗分经典的多线程并发协作的模式,弄懂⽣产者-消费者问题能够让我们对并发编程的理解加深。

所谓⽣产者-消费者问题,实际上主要是包含了两类线程,⼀种是⽣产者线程⽤于⽣产数据,另⼀种是消费者线程⽤于消费数据,为了解耦⽣产者和消费者的关系,通常会采⽤共享的数据区域,就像是⼀个仓库,⽣产者⽣产数据之后直接放置在共享数据区中,并不需要关⼼消费者的⾏为;⽽消费者只需要从共享数据区中去获取数据,就不再需要关⼼⽣产者的⾏为。

但是,这个共享数据区域中应该具备这样的线程间并发协作的功能:
本⽂的⽣产者消费者模型
但是本篇⽂章不是说的多线程问题,⽽是为了完成⼀个功能,设置⼀个⼤⼩固定的⼯⼚,⽣产者不断的往仓库⾥⾯⽣产数据,消费者从仓库⾥⾯消费数据,功能类似于⼀个队列,每⼀次⽣产者⽣产数据放到队尾,消费者从头部不断消费数据,如此循环处理相关业务。

代码
下⾯是⼀个泛型的⼯⼚类,可以不断的⽣产数据,消费者不断的消费数据。

//
// 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帧数据作为⼀个分组处理任务,可以⽤下⾯的⽅法来实现。

相关文档
最新文档