#include <QCoreApplication>
#include <QWaitCondition>
#include <QQueue>
#include <QMutex>
#include <QThread>
#include <QDebug>
template <typename T>
class BlockingQueue
{
public:
BlockingQueue(){}
void put(const T& value)
{
QMutexLocker locker(&m_mutex);
m_queue.enqueue(value);
m_condition.wakeOne();//唤醒等待队列中的一个线程
}
T tack()
{
QMutexLocker locker(&m_mutex);
while (m_queue.isEmpty())
{
m_condition.wait(&m_mutex);
}
return m_queue.dequeue();
}
bool isEmpty() const
{
QMutexLocker locker(&m_mutex);
return m_queue.isEmpty();
}
int size() const
{
QMutexLocker locker(&m_mutex);
return m_queue.size();
}
private:
QQueue<T> m_queue;
mutable QMutex m_mutex;
QWaitCondition m_condition;
};
static BlockingQueue<int> queue;
class Producer :public QThread
{
public:
void run() override
{
for (int i = 0; i < 10; i++)
{
queue.put(i);
qDebug() << "Producer thread: " << QThread::currentThreadId() << ", value: " << i;
msleep(500);
}
}
};
class Consumer:public QThread
{
public:
void run() override
{
int value = 0;
while (true)
{
value = queue.tack();
qDebug() << "Consumer thread: " << QThread::currentThreadId() << ", value: " << value;
}
}
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Producer producer;
Consumer consumer1, consumer2;
producer.start();
consumer1.start();
consumer2.start();
return a.exec();
}