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帧数据作为一个分组处理任务,可以用下面的方法来实现。

posted @ 2019-06-19 15:17  牧轩居士  阅读(10513)  评论(0编辑  收藏  举报