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();

1176527-20190619151105279-2096294394.png

用途

该类可以很方便的实现分组问题,比如处理视频序列时候将第i帧到第j帧数据作为一个分组处理任务,可以用下面的方法来实现。

转载于:https://www.cnblogs.com/muxuan/p/11051448.html

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值