共计 1527 个字符,预计需要花费 4 分钟才能阅读完成。
信号量的方法解决生产与消费者的问题,通过申请读写空间的成功与失败进行相应的线程运行与阻塞达到目的。要是生产者线程结束去唤醒消费者也是一个解决问题的思路,消费者消费之后去唤醒生产者线程,这样就可以解决生产者与消费者的问题。甲壳虫闪亮登场。。。。
#include <QThread>
#include <QtDebug>
#include <QMutex>
#include <QWaitCondition>
#include <iostream>
#include <QCoreApplication>
QWaitCondition bufferEmpty;
QWaitCondition bufferFull;
QMutex mutex;
const int DataSize = 1000;
const int BufferSize = 80;
int buffer[BufferSize];
int numUsedBytes = 0;
int rIndex = 0;
class Producer :
public QThread
{
public:
Producer();
~Producer();
void run();
};
Producer::Producer()
{
}
Producer::~Producer()
{
}
void Producer::run()
{
for (int i = 0; i < DataSize; i++)
{
mutex.lock();
if (numUsedBytes == BufferSize)
bufferEmpty.wait(&mutex); //容量已满,生产者阻塞
buffer[i%BufferSize] = i%BufferSize;
numUsedBytes++; //用来记录当前缓冲区是否已满
bufferFull.wakeAll(); //缓冲区有容量,唤醒消费者
mutex.unlock();
}
}
class Comsumer :
public QThread
{
public:
Comsumer();
~Comsumer();
void run();
};
Comsumer::Comsumer()
{
}
Comsumer::~Comsumer()
{
}
void Comsumer::run()
{
forever
{
mutex.lock();
if (numUsedBytes == 0)
bufferFull.wait(&mutex); //容量为空,阻塞消费者
qDebug() << currentThreadId() << buffer[rIndex%BufferSize];
rIndex=(++rIndex)%BufferSize;
numUsedBytes--;
bufferEmpty.wakeAll(); //缓冲区未满,唤醒生产者
mutex.unlock();
}
std::cout << std::endl;
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Producer producer;
Comsumer consumerA;
Comsumer consumerB;
producer.start();
consumerA.start();
consumerB.start();
producer.wait();
consumerA.wait();
consumerB.wait();
return a.exec();
}
//forever用法定义,比c++高端,略叼
#define Q_FOREVER for(;;)
#ifndef QT_NO_KEYWORDS
# ifndef foreach
# define foreach Q_FOREACH
# endif
# ifndef forever
# define forever Q_FOREVER
# endif
#endif
正文完
请博主喝杯咖啡吧!