http://blog.csdn.net/lincyang/article/details/5769889
参考自《精通qt4编程》。
qt为实现线程的同步与互斥,提供了几个类。
下面主要介绍三个类:
一、QMutex和QMutexLocker
- class key
- {
- public:
- key(){key = 0;}
- int createKey(){QMutexLocker locker(&mutex);++key;return key;}
- int value() const {QMutexLocker locker(&mutex);return key;}
- private:
- int key;
- Qmutex mutex;
- };
二、QSemaphore
- #include <QtCore>
- #include <stdio.h>
- #include <stdlib.h>
- const int DataSize = 100000;
- const int BufferSize = 8192;
- int buffer[BufferSize];
- QSemaphore freeBytes(BufferSize);
- QSemaphore usedBytes(0);
- class Producer : public QThread
- {
- public:
- void run();
- };
- void Producer::run()
- {
- for (int i = 0; i < DataSize; ++i) {
- freeBytes.acquire();
- buffer[i % BufferSize] = (i % BufferSize);
- usedBytes.release();
- }
- }
- class Consumer : public QThread
- {
- public:
- void run();
- };
- void Consumer::run()
- {
- for (int i = 0; i < DataSize; ++i) {
- usedBytes.acquire();
- fprintf(stderr, "%d ", buffer[i % BufferSize]);
- if(i % 16 ==0 && i!=0)
- fprintf(stderr, "/n");
- freeBytes.release();
- }
- fprintf(stderr, "/n");
- }
- int main(int argc, char *argv[])
- {
- QCoreApplication app(argc, argv);
- Producer producer;
- Consumer consumer;
- producer.start();
- consumer.start();
- producer.wait();
- consumer.wait();
- // return 0;
- return app.exec();
- }
三、QWaitCondition
- #include <QtCore>
- #include <stdio.h>
- #include <stdlib.h>
- const int DataSize = 10000;
- const int BufferSize = 8192;
- int buffer[BufferSize];
- QWaitCondition bufferEmpty;
- QWaitCondition bufferFull;
- QMutex mutex;
- int numUsedBytes = 0;
- int rIndex=0;
- class Producer : public QThread
- {
- public:
- void run();
- };
- void Producer::run()
- {
- for (int i = 0; i < DataSize; ++i) {
- mutex.lock();
- if (numUsedBytes == BufferSize)
- bufferEmpty.wait(&mutex);
- // mutex.unlock();
- buffer[i % BufferSize] = numUsedBytes;
- // mutex.lock();
- ++numUsedBytes;
- bufferFull.wakeAll();
- mutex.unlock();
- }
- }
- class Consumer : public QThread
- {
- public:
- void run();
- };
- void Consumer::run()
- {
- forever {
- mutex.lock();
- if (numUsedBytes == 0)
- bufferFull.wait(&mutex);
- // mutex.unlock();
- printf("%ul::[%d]=%d->%d /n", currentThreadId (),rIndex,buffer[rIndex],numUsedBytes);
- // mutex.lock();
- rIndex = (++rIndex)%BufferSize;
- --numUsedBytes;
- bufferEmpty.wakeAll();
- mutex.unlock();
- }
- printf("/n");
- }
- int main(int argc, char *argv[])
- {
- QCoreApplication app(argc, argv);
- for (int i = 0; i < BufferSize; ++i) {
- buffer[i ] = -1;
- }
- Producer producer;
- Consumer consumerA;
- Consumer consumerB;
- producer.start();
- consumerA.start();
- consumerB.start();
- producer.wait();
- consumerA.wait();
- consumerB.wait();
- return 0;
- }
上面用QSemaphore和QWaitCondition两个类完成生产者和消费者实例,对
我们实际工作很有益处。