Qt基於QSemaphore的生產者消費者模型

晚餐吃什麼發表於2018-11-09
#include <QCoreApplication>
#include <QThread>

#include <QSemaphore>
#include <QDebug>


int dataSize=80;
int bufferSize=40;
QSemaphore usedSemaphore(0);
QSemaphore freeSemaphore(bufferSize);
int arr[40];

class Producer:public QThread{
protected:
    void run(){
        for(int i=0;i<dataSize;i++){
            freeSemaphore.acquire();
            arr[i%bufferSize]=i;
            usedSemaphore.release();
        }
    }
};

class Consumer:public QThread{
protected:
    void run(){
        for(int i=0;i<dataSize;i++){
            usedSemaphore.acquire();
            qDebug()<<arr[i%bufferSize];
            freeSemaphore.release();
        }
    }
};

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    Producer thread1;
    Consumer thread2;
    thread2.start();
    thread1.start();
    thread1.wait();
    thread2.wait();

    return a.exec();
}

 

相關文章