Qt notes --QSemaphore processing producer / consumer model

table of Contents

Producer-consumer model

Manual Readings

main.cpp

.pro

operation result


Producer-consumer model

Reprinted: https: //blog.csdn.net/u011109589/article/details/80519863

Brief introduction

In the actual software development process, often encounter the following scene: a module responsible for generating data, which is responsible for processing by another module (module here is broad, can be classes, functions, threads, processes, etc. ). Data generation module, it is aptly called producer; and data processing module, called the consumer.

    Abstract only producers and consumers, but also is not enough on the producer / consumer model. This mode also need to have a buffer in between producers and consumers, as an intermediary. Manufacturer data into the buffer, data taken from the buffer and the consumer. The following approximate structure of FIG.

   In order not to be too abstract, we give an example to send a letter (though no longer fashionable these days to send a letter, but this example is quite apt). Suppose you want to send an ordinary letter, roughly as follows:

    1, you write the letter - the equivalent of the maker of data

    2, you put the letter into the mailbox - the equivalent of producers to put data into the buffer

    3, the letter was removed from the mailbox postman - data fetch buffer corresponding to the consumer

    4, the post office postman take the letter corresponding processing - processing data corresponding to consumer

   advantage

   Some students may be asked: What is the use of this buffer pinching? Why not call a function directly to the producers of consumer, to pass data directly in the past? Come up with such a buffer for?

    In fact, there is great stress, probably has the following advantages.

   Decoupling

    Assuming that producers and consumers are the two classes. If you let the producer directly calling a method of consumers, then consumers will have to rely on producers (ie coupling). If consumers in the future code changes may affect producers. If both rely on a buffer, not directly dependent therebetween, coupled correspondingly reduced.

    Following the above example, if you do not use the mailbox (ie, buffer), you have to put the letter directly to the postman. Some students will say that directly to the postman is not a very simple thing? In fact, not simple, you have to know who is the postman, in order to give the letter to him (alone wearing uniforms, in case it was fake, will suffer). This dependency between the generation and you and the postman (the equivalent of the strong coupling of producers and consumers). If one day the postman substitutions, you have to re-learn what (equivalent modifications lead to changes in consumer producer Code). While the relatively fixed mailbox, you depend on it relatively low cost (and corresponding to the weak coupling between the buffer).

    ◇ supports concurrency (concurrency)

    Producer consumers directly call a method, there are other drawbacks. Since the function call is synchronous (or call blocking), the method does not return before the consumers, the producers had been waiting over there. In case the consumer data processing is slow, the producer would spoil the good times in vain.

    After using the producer / consumer model, producers and consumers may be two independent concurrent body (common type of concurrent processes and threads there are two, behind the post will speak at two concurrent application types). Manufacturer data into the buffer produced a lost production can go to the next data. Basically do not rely on the consumer's processing speed.

    In fact, when this mode is mainly used to deal with concurrency issues.

    Examples send a letter from view. If there is no mailbox, you have to hand the letter over silly standing in the intersection waiting for the postman to close (the equivalent of obstruction producer); or if the postman was going door to door to ask, who will send a letter (the equivalent of consumers polled). Either way, all kind of soil.

    ◇ support busy uneven

    Buffer has another advantage. If the speed or slower manufacturing data faster, the benefits of the buffer is manifested. When the fast manufacturing data, consumers time to process, unprocessed data can be temporarily stored in the buffer. Manufacturing speed slow down the producer, consumer and then slowly disposed of.

    In order to fully reuse, for example we have a chance to send a letter of thing. Assuming that the postman can only take 1000 letter. In case a particular hit Valentine's Day (Christmas may be) to send greeting cards, we need to send out a letter over 1000, this time the mailbox This buffer comes in handy. Postman too late to take away the letter in the mailbox in the staging, so next time take over.

    Costs so much saliva, hope do not understand the original producer / consumer model students can understand how it was all about. Then talk data unit.

   Data Unit

    What data unit pinched? Briefly, each producer into the buffer is a data unit; removed from the buffer each time the consumer, but also a data unit. For example, before a message send a letter, we can seal each letter as a separate data unit.

    But just such a presentation, too simple, does not contribute to the analysis and talk this thing out. Therefore, we look behind the data unit needs to have properties which. After thoroughly understand these characteristics, it is easy to analyze the complex business logic out something suitable for the data unit.

 

 Manual Readings

https://doc.qt.io/qt-5/qsemaphore.html#details

Mutex semaphores are summarized. Although the mutex is locked only once, but many times it is possible to acquire the semaphore. Semaphore commonly used to protect a certain number of identical resources.

Semaphore supports two basic operations, acquire () and release ()

 

main.cpp

#include <QCoreApplication>
#include <QSemaphore>
#include <QThread>
#include <stdio.h>

const int DataSize = 1000;
const int BufferSize = 80;

int buffer[BufferSize];//生产者向buffer中写入数据,消费者读取前者的数据,可以减少信号量带来的开销
QSemaphore freeBytes(BufferSize);//控制被生产者填充的缓冲区部分
QSemaphore usedBytes(0); //控制可被消费者读取的缓冲区部分

//生产者
class Producer:public QThread{
public:
    Producer();
    void run();
};

void Producer::run(){
    for(int i=0;i<DataSize;i++){
        freeBytes.acquire();//获取空闲的数据单元
        buffer[i%BufferSize]=(i%BufferSize);//使用当前缓冲区单元序号填写这个缓冲区单元
        usedBytes.release();//释放资源
    }
}

Producer::Producer(){

}

//消费者
class Consumer:public QThread{
public:
    Consumer();
    void run();
};

void Consumer::run(){
    for(int i=0;i<DataSize;i++){
        usedBytes.acquire();//消费者获取可被读取的数据单元
        fprintf(stderr,"%d",buffer[i%BufferSize]);//当消费者成功获取数据单元,打印下来
        if(i%16==0&&i!=0){
            fprintf(stderr,"\n");
        }
        freeBytes.release();//释放其数据单元供给下次生产者填充
    }
    fprintf(stderr,"\n");
}

Consumer::Consumer(){

}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    Producer producer;
    Consumer consumer;

    //启动消费者和生产者的线程
    producer.start();
    consumer.start();

    //等待消费者执行完毕后退出
    producer.wait();
    consumer.wait();

    return a.exec();
}

.pro

QT += core
QT -= gui

CONFIG += c++11

TARGET = Semaphore
CONFIG += console
CONFIG -= app_bundle

TEMPLATE = app

SOURCES += main.cpp

# The following define makes your compiler emit warnings if you use
# any feature of Qt which as been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS

# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

operation result

Published 250 original articles · won praise 267 · views 110 000 +

Guess you like

Origin blog.csdn.net/qq_41895747/article/details/104102307
Recommended