16:50:392017-03-31
本文章为原创,如若引用请指明出处,否则追责。
以 生产、消费者的例子说明
#include <QtCore/QCoreApplication>
#include <QWaitCondition>#include <QThread>#include <QMutex>#include <iostream>const int DataSize = 100;
const int BufferSize = 1;char buffer[BufferSize];QWaitCondition bufferIsNotFull;
QWaitCondition bufferIsNotEmpty;QMutex mutex;int usedSpace;
class Producer : public QThread
{ protected: void run() { for (int i = 0; i < DataSize; ++i) { mutex.lock();//A while (usedSpace == BufferSize) { bufferIsNotFull.wait(&mutex);//B } std::cerr<<"P";//C ++usedSpace; bufferIsNotEmpty.wakeAll(); mutex.unlock(); } }//…G};class Consumer : public QThread
{ protected: void run() { for (int i = 0; i < DataSize; ++i) { mutex.lock();//D while (usedSpace == 0) { bufferIsNotEmpty.wait(&mutex);//E } std::cerr<<"C";//F --usedSpace; bufferIsNotFull.wakeAll(); mutex.unlock(); } std::cerr<<std::endl; }//…K};int main(int argc, char *argv[])
{ Producer producer; Consumer consumer; producer.start(); consumer.start(); producer.wait(); consumer.wait();return 0;}
根据QWaitCondition::wait(lockedMutex)的说明:Releases the lockedMutex and waits on the wait condition. The lockedMutex must be initially locked by the calling thread.
在调用wait之前应将lockedMutex锁住 见上面代码的B和A处,以及E、D处的调用关系。
之所以先执行Releases the lockedMutex 是因为,调用wait(lockedMutex)后程序直接跳转到G(执行完B)或K处(执行完D),而不再执行C、F处的代码,所以要release the lockedmutex
否则不能保证mutex的lock、unlock的成对执行。