基于QT实现的生产者消费者模型
不足之处请留言指出
//global.h
#ifndef GLOBAL_H
#define GLOBAL_H
#include
#include
#include
extern QMutex g_mutex;
extern QWaitCondition g_bufferFull;
extern QWaitCondition g_bufferEmpty;
#endif// GLOBAL_H
//global.cpp
#include
#include "global.h"
QMutex g_mutex;
QWaitCondition g_bufferFull;
QWaitCondition g_bufferEmpty;
//Resource.h
#ifndef RESOURCE_H
#define RESOURCE_H
#include
class Resource : public QObject
{
Q_OBJECT
public:
explicit Resource(QObject *pParent = NULL);
void push(QByteArray byte);
void popup();
signals:
void dataChanged(const QByteArray&);
public slots:
private:
int m_index;
bool m_flag;
};
#endif // RESOURCE_H
//Resource.cpp
#include
#include "global.h"
#include "Resource.h"
Resource::Resource(QObject *pParent)
: QObject(pParent),
m_index(0),
m_flag(false)
{
}
void Resource::push(QByteArray byte)
{
QMutexLocker locker(&g_mutex);
while (m_flag == true)
{
g_bufferFull.wait(&g_mutex);
}
qDebug()<<"Producer:"<<++m_index;
m_flag = true;
g_bufferEmpty.wakeAll();
}
void Resource::popup()
{
QMutexLocker locker(&g_mutex);
while (m_flag == false)
{
g_bufferEmpty.wait(&g_mutex);
}
qDebug()<<" Consumer:"<<m_index;
m_flag = false;
g_bufferFull.wakeAll();
}
//Producer.h
#ifndef PRODUCER_H
#define PRODUCER_H
#include
#include "Resource.h"
class Producer : public QThread
{
Q_OBJECT
public:
explicit Producer(Resource &res, QObject *parent = 0);
protected:
void run();
signals:
public slots:
private:
Resource &m_res;
};
#endif // PRODUCER_H
//Producer.cpp
#include
#include "global.h"
#include "Producer.h"
Producer::Producer(Resource &res, QObject *parent)
: QThread(parent),
m_res(res)
{
}
void Producer::run()
{
// while (true)
for (int i=0; i<30; ++i)
{
/****************** 测试数据 ******************/
QByteArray byte;
QDataStream out(&byte, QIODevice::WriteOnly);
QString time = QTime::currentTime().toString("hh:mm:ss");
out<