Qtは--QMutex&QWaitCondition処理する生産者 - 消費者モデルノート

QSemaphore処理プロデューサ/コンシューマモデル:

https://blog.csdn.net/qq_41895747/article/details/104102307

 

main.cppに

#include <QCoreApplication>
#include <QMutex>
#include <QThread>
#include <QWaitCondition>
#include <stdio.h>

const int DataSize = 1000;//数据区大小
const int BufferSize = 80;//缓冲区大小

int buffer[BufferSize];
QWaitCondition bufferEmpty;
QWaitCondition bufferFull;
QMutex mutex;//锁定的互斥量,使用互斥量保证操作的原子性
int numUseBytes=0;//可用字节
int rIndex=0;//当前读取缓冲区的位置

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

Producer::Producer(){

}

void Producer::run(){
    for(int i=0;i<DataSize;i++){
        mutex.lock();//锁定互斥量
        if(numUseBytes==BufferSize){//检查缓冲区是否已经填满
            bufferEmpty.wait(&mutex);//等待缓冲区有空位
        }
        buffer[i%BufferSize]=numUseBytes;//使用当前缓冲区单元序号填写这个缓冲区单元
        ++numUseBytes;//可用字节数增一
        bufferFull.wakeAll();//唤醒等待缓冲区有可用数据为真的线程
        mutex.unlock();//解锁互斥量
    }
}

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

Consumer::Consumer(){

}

void Consumer::run(){
    forever{
        mutex.lock();//锁定互斥量
        if(numUseBytes==0){
            bufferFull.wait(&mutex);
        }
        //打印当前线程号、缓冲区位置、缓冲区数据
        printf("%ul::[%d]\n",currentThreadId(),rIndex,buffer[rIndex]);//
        rIndex=(++rIndex)%BufferSize;//变量循环加一
        bufferFull.wakeAll();//唤醒等待缓冲区有可用数据为真的线程
        mutex.unlock();//解锁互斥量
    }
    printf("\n");
}

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

    Producer producer;
    Consumer consumerA;
    Consumer consumerB;

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

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

    return a.exec();
}

。プロ

QT += core
QT -= gui

CONFIG += c++11

TARGET = WaitCondition
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

業績

 

公開された251元の記事 ウォンの賞賛268 ビュー110 000 +

おすすめ

転載: blog.csdn.net/qq_41895747/article/details/104103066