#include <QThread>
#include <QMutex>
#include <QWaitCondition>
#include <QQueue>
#include <QVariant>
#include <iostream>
const int DataSize = 100;
const int BufferSize = 20;
QQueue<QVariant> queue;
QWaitCondition bufferIsNotFull;
QWaitCondition bufferIsNotEmpty;
QMutex mutex;
QMutex printMutex;
void print(int flag,int var)
{
printMutex.lock();
if(flag == 0)
std::cout<<"set:"<<var<<std::endl;
else
std::cout<<"get:"<<var<<std::endl;
printMutex.unlock();
}
class Producer : public QThread
{
public:
void run();
};
void Producer::run()
{
for(int i = 0; i < DataSize; ++i)
{
mutex.lock();
while(queue.size() == BufferSize)
bufferIsNotFull.wait(&mutex);
int var = std::rand()%10;
print(0,var);
queue.append(var);
bufferIsNotEmpty.wakeAll();
mutex.unlock();
}
}
class Consumer : public QThread
{
public:
void run();
};
void Consumer::run()
{
while(1)
{
mutex.lock();
while(queue.isEmpty())
bufferIsNotEmpty.wait(&mutex);
int var = queue.dequeue().toInt();
print(1,var);
bufferIsNotFull.wakeAll();
mutex.unlock();
}
}
int main()
{
Producer producer1;
Consumer consumer1;
Producer producer2;
Consumer consumer2;
producer1.start();
consumer1.start();
producer2.wait();
consumer2.wait();
system("pause");
return 0;
}