码迷,mamicode.com
首页 > 其他好文 > 详细

QWaitCondition实现生产者与消费者

时间:2020-07-12 14:27:51      阅读:69      评论:0      收藏:0      [点我收藏+]

标签:release   sign   void   条件变量   wak   ++i   otf   iostream   缓存   

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;
}

QWaitCondition实现生产者与消费者

标签:release   sign   void   条件变量   wak   ++i   otf   iostream   缓存   

原文地址:https://blog.51cto.com/14854104/2510145

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!