指標定義
#ifndef DEFINE_H
#define DEFINE_H
#include <QMetaType>
struct Message{
int index;
int *data;
};
typedef int* iPoint;
Q_DECLARE_METATYPE(Message)
#endif // OBJECT1_H
業務模組1
#ifndef OBJECT1_H
#define OBJECT1_H
#include <QObject>
#include "define.h"
class object1 : public QObject
{
Q_OBJECT
public:
explicit object1(QObject *parent = nullptr);
signals:
void sigSendMsg(const Message&);
public slots:
void onRevPointer(iPoint);
private:
class QThread *worker;
int index_;
};
#endif // OBJECT1_H
#include "object1.h"
#include <QThread>
#include <QTimer>
#include <QDebug>
object1::object1(QObject *parent) : QObject(parent)
{
index_ = 0;
QTimer *t = new QTimer(this);
t->setInterval(1000);
connect(t,&QTimer::timeout,this,[this](){
Message msg;
msg.index = ++index_;
msg.data = new int[1024*1024];
sigSendMsg(msg);
qDebug()<<"send thread:"<<QThread::currentThreadId();
});
t->start();
worker = new QThread();
worker->setObjectName("object1");
this->moveToThread(worker);
worker->start();
}
void object1::onRevPointer(iPoint p)
{
qDebug()<<p[0];
delete p;//不刪除會有記憶體洩露
qDebug()<<Q_FUNC_INFO;
}
業務模組2
#ifndef OBJECT2_H
#define OBJECT2_H
#include <QObject>
#include "define.h"
class object2 : public QObject
{
Q_OBJECT
public:
explicit object2(QObject *parent = nullptr);
public slots:
void onRevMsg(const Message&);
signals:
void sigSendPointer(iPoint);
private:
class QThread *worker;
int index_;
};
#endif // OBJECT2_H
//
#include "object2.h"
#include <QThread>
#include <QTimer>
#include <QDebug>
object2::object2(QObject *parent) : QObject(parent)
{
index_ = 0;
QTimer *t = new QTimer(this);
t->setInterval(1000);
connect(t,&QTimer::timeout,this,[this](){
iPoint p = new int [1024*1024];
p[0] = ++index_;
sigSendPointer(p);
});
t->start();
worker = new QThread();
worker->setObjectName("object2");
this->moveToThread(worker);
worker->start();
}
void object2::onRevMsg(const Message & msg)
{
qDebug()<<"rev:"<<msg.index;
delete msg.data;//不刪除會有記憶體洩露
qDebug()<<"rev thread:"<<QThread::currentThreadId();
}
連線
#include <QCoreApplication>
#include "object1.h"
#include "object2.h"
#include <QThread>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
qDebug()<<"Main thread:"<<QThread::currentThreadId();
object1 *o1 = new object1;
object2 *o2 = new object2;
qRegisterMetaType<Message>("Message");//註冊
qRegisterMetaType<iPoint>("iPoint");//註冊
QObject::connect(o1,&object1::sigSendMsg,o2,&object2::onRevMsg);
QObject::connect(o2,&object2::sigSendPointer,o1,&object1::onRevPointer);
return a.exec();
}