QSemaphore类提供了强壮的整数信号量。
QSemaphore也可以被用来使线程的执行顺序化,和QMutex的方法相似。信号量和互斥量的不同在于,信号量可以在同一时间被多于一个的线程访问。
/*
*一个生产者 多个消费者情况,,使用 QSemaphore线程同步
*
*/
#include <QCoreApplication>
#include <thread>
#include <QSemaphore>
#include <iostream>
#include <QThread>
#include <QMutex>
using namespace std;
int dataSize = 100;
const int buffSize = 10;
int buff[102] = {0};
QSemaphore unUsedCount(buffSize);
QSemaphore usedCount(0);
QMutex mutex1;
int j = 0;
void makeData()
{
for(int i=0;i<dataSize;i++)
{
unUsedCount.acquire();
buff[i] = i;
usedCount.release();
}
}
void usedData()
{
for(;j<dataSize;)
{
usedCount.acquire();
mutex1.lock();
cout<< QThread::currentThreadId() <<" is used: " <<buff[j] << endl;
mutex1.unlock();
unUsedCount.release();
j++;
QThread::msleep(1000);
}
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
thread *t1 = nullptr;
t1 = new thread(makeData);
t1->detach();
thread *t2 = new thread(usedData);
t2->detach();
thread *t3 = new thread(usedData);
t3->detach();
thread *t4 = new thread(usedData);
t4->detach();
thread *t5 = new thread(usedData);
t5->detach();
return a.exec();
}