producer_customer.h
#include <QThread>
class Producer : public QThread
{
public:
Producer();
protected:
void run();
};
class Customer : public QThread
{
public:
Customer();
protected:
void run();
};
producer_customer.h
#include "producer_customer.h"
#include <QWaitCondition>//等待条件
#include <QMutex>
#include <QDebug>
QWaitCondition cond;
QMutex mutex;
int global = 0;
int flag = 0;
Producer::Producer()
{
}
void Producer::run()
{
while(1)
{
mutex.lock();
int tmp = global;
global += 2;
qDebug()<< currentThreadId()
<< ", Producer: "
<< tmp
<< "-->"
<< global;
//判定标志,是否有人在等待
while(!flag)
{
mutex.unlock();
usleep(200);
mutex.lock();
}
cond.wakeAll();//唤醒所有消费者
//cond.wakeOne();
qDebug() << "producer finished! ----------------------";
//只唤醒一个处于等待的消费者
mutex.unlock();
sleep(2);
}
}
Customer::Customer()
{
}
void Customer::run()
{
while(1)
{
mutex.lock();
//++
flag ++;
cond.wait(&mutex);//等待生产者唤醒消费
//--
flag --;
int tmp = global;
global--;
qDebug()<< currentThreadId()
<< ", Customer: "
<< tmp
<< "-->"
<< global;
qDebug() << "customer finished!================";
mutex.unlock();
sleep(1);
}
}
main.cpp
#include <QApplication>
#include <QDebug>
#include "producer_customer.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Producer *p = new Producer;
Customer *c1 = new Customer;
Customer *c2 = new Customer;
p->start();
c1->start();
c2->start();
return a.exec();
}