- /*
- 使用QWaitCondition和QMutex可以实现比信号量更精确的控制
- */
- #include <QtCore>
- #include <iostream>
- //const int DataSize = 100000;
- //const int BufferSize = 4096;
- const int DataSize = 100;
- const int BufferSize = 100;
- char buffer[BufferSize];
- //与信号量不同的程序
- QWaitCondition bufferIsNotFull; //QWaitCondition允许在一定条件下触发其它多个线程
- 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();//锁定:保护对usedSpace变量的访问
- //如果缓冲区都是用过的字节,那么就等待
- while (usedSpace == BufferSize)
- bufferIsNotFull.wait(&mutex);//wait的过程:解锁->阻塞当前线程->满足条件->锁定->返回
- buffer[i % BufferSize] = "ACGT"[uint(rand()) % 4];
- std::cerr<<"P";//代表一次生产者线程的运行
- ++usedSpace;
- bufferIsNotEmpty.wakeAll();//Wakes all threads waiting on the wait condition.
- mutex.unlock();//解锁
- }
- }
- //消费者
- class Consumer : public QThread
- {
- public:
- void run();
- };
- void Consumer::run()
- {
- for (int i = 0; i < DataSize; ++i) {
- mutex.lock();//
- //如果缓冲区里“用过的”字节数目为0,则等待
- while (usedSpace == 0)
- bufferIsNotEmpty.wait(&mutex);
- //std::cerr << buffer[i % BufferSize];
- char Cons = buffer[i % BufferSize];
- std::cerr<<"c";
- --usedSpace;
- bufferIsNotFull.wakeAll();
- mutex.unlock();
- }
- std::cerr << std::endl;
- }
- int main()
- {
- Producer producer;
- Consumer consumer;
- producer.start();
- consumer.start();
- producer.wait();
- consumer.wait();
- return 0;
- }
QWaitCondition
最新推荐文章于 2024-02-14 17:13:28 发布