Qt基于QSemaphore的生产者消费者模型
程序员文章站
2022-06-04 22:00:37
...
#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();
}