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 <QtCore>
include <iostream>
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;
}