傳統的生產者消費者模型
生產者-消費者模式是一個十分經典的多線程並發協作的模式,弄懂生產者-消費者問題能夠讓我們對並發編程的理解加深。所謂生產者-消費者問題,實際上主要是包含了兩類線程,一種是生產者線程用於生產數據,另一種是消費者線程用於消費數據,為了解耦生產者和消費者的關系,通常會采用共享的數據區域,就像是一個倉庫,生產者生產數據之后直接放置在共享數據區中,並不需要關心消費者的行為;而消費者只需要從共享數據區中去獲取數據,就不再需要關心生產者的行為。但是,這個共享數據區域中應該具備這樣的線程間並發協作的功能:
本文的生產者消費者模型
但是本篇文章不是說的多線程問題,而是為了完成一個功能,設置一個大小固定的工廠,生產者不斷的往倉庫里面生產數據,消費者從倉庫里面消費數據,功能類似於一個隊列,每一次生產者生產數據放到隊尾,消費者從頭部不斷消費數據,如此循環處理相關業務。
代碼
下面是一個泛型的工廠類,可以不斷的生產數據,消費者不斷的消費數據。
//
// 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幀數據作為一個分組處理任務,可以用下面的方法來實現。