QWaitCondition实现生产者与消费者

The QWaitCondition class provides a condition variable for synchronizing threads.
//为同步线程提供条件变量

bool QWaitCondition::wait(QMutex *lockedMutex, unsigned long time = ULONG_MAX)
Releases the lockedMutex and waits on the wait condition.
//释放lockedMutex并等待条件

void QWaitCondition::wakeAll()
Wakes all threads waiting on the wait condition.
激活所有等待 等待条件的thread

include

include

const int DataSize = 100000;
const int BufferSize = 4096;
char buffer[BufferSize];

QWaitCondition bufferIsNotFull;
QWaitCondition bufferIsNotEmpty;
QMutex mutex;
int usedSpace = 0;

class Producer : public QThread
{
public:

void run();

};

void Producer::run()
{

for (int i = 0; i < DataSize; ++i) {
    mutex.lock();
    while (usedSpace == BufferSize)//已经填满了缓冲区,是满的
        bufferIsNotFull.wait(&mutex); //等待 bufferIsNotFull
    /***还有空间填充  **/
    buffer[i % BufferSize] = "ACGT"[uint(std::rand()) % 4];
    ++usedSpace;
    bufferIsNotEmpty.wakeAll();//填充了之后,缓存区是非空的,会唤醒等待bufferIsNotEmpty的线程
    mutex.unlock();
}

}

class Consumer : public QThread
{
public:

void run();

};

void Consumer::run()
{

for (int i = 0; i < DataSize; ++i)
{
    mutex.lock();
    while (usedSpace == 0)// 缓存区没有任何数据,就是空的
        bufferIsNotEmpty.wait(&mutex);//等待bufferIsNotEmpty
    /*** 缓存区有数据 **/
    std::cerr << buffer[i % BufferSize];
    --usedSpace;
    bufferIsNotFull.wakeAll();//消费了数据后,缓存区是非满的,会唤醒等待bufferIsNotFull的线程
    mutex.unlock();
}
std::cerr << std::endl;

}

int main()
{

Producer producer;
Consumer consumer;
producer.start();
consumer.start();
producer.wait();
consumer.wait();
return 0;

}

你可能感兴趣的:(qt5)