参考
线程参考 https://blog.csdn.net/jinhucheng/article/details/70371724
udp参考 https://blog.csdn.net/weixin_42216430/article/details/80780297
思路
proc.moveToThread(&thread);//proc中所有的槽都会在另一个线程(thread)中执行
UdpReceiver
槽receive 监听udp报文,把监听到的报文放入一个线程安全的容器C,抛出 readyProcess信号
Processor
readyProcess 触发processUdp槽,从容器C拿出数据进行处理
代码
#ifndef UDPRECEIVER_H
#define UDPRECEIVER_H
#include <QObject>
#include <QUdpSocket>
class UdpReceiver : public QObject
{
Q_OBJECT
public:
explicit UdpReceiver(QObject *parent = nullptr);
~UdpReceiver();
signals:
/**
* @brief 在receive槽中抛出它,表明可以进行下一步的费时处理
*/
void readyProcess();
public slots:
/**
* @brief 将readyRead信号与它连接
*/
void receive();
private:
QUdpSocket *udpSocket;
};
#endif // UDPRECEIVER_H
#include "udpreceiver.h"
#include <QByteArray>
#include <QThread>
UdpReceiver::UdpReceiver(QObject *parent) : QObject(parent)
{
udpSocket = new QUdpSocket;
udpSocket->bind(QHostAddress("127.0.0.1"), 4567);
connect(udpSocket, SIGNAL(readyRead()), this, SLOT(receive()));
}
UdpReceiver::~UdpReceiver()
{
delete udpSocket;
}
void UdpReceiver::receive()
{
qDebug()<<"thread "<<QThread::currentThreadId()<<"receive";
QByteArray ba;
while(udpSocket->hasPendingDatagrams())
{
ba.resize(udpSocket->pendingDatagramSize());
udpSocket->readDatagram(ba.data(), ba.size());
qDebug()<< ba.data();
}
//将数据放进一个共享的互斥容器C
emit readyProcess();
}
#ifndef PROCESSOR_H
#define PROCESSOR_H
#include <QObject>
/**
* @brief 处理UDP监听到的数据
*/
class Processor : public QObject
{
Q_OBJECT
public:
explicit Processor(QObject *parent = nullptr);
signals:
public slots:
/**
* @brief 复杂的处理报文操作
*/
void processUdp();
};
#endif // PROCESSOR_H
#include "processor.h"
#include <QThread>
#include <QDebug
Processor::Processor(QObject *parent) : QObject(parent)
{
}
void Processor::processUdp(){
qDebug()<<"thread "<<QThread::currentThreadId()<<"start process ";
//从共享的容器C中取数据
//代表复杂的操作
int i=1000000000;
while(i-->0){}
qDebug()<<"process done";
}
#include <QCoreApplication>
#include "udpreceiver.h"
#include "processor.h"
#include <QThread>
int main(int argc, char *argv[])
{
qDebug()<<"main thread "<<QThread::currentThreadId();
QCoreApplication a(argc, argv);
QThread thread;
UdpReceiver rec;
Processor proc;
proc.moveToThread(&thread);//proc中所有的槽都会在另一个线程中执行
QObject::connect(&rec, SIGNAL(readyProcess()), &proc, SLOT(processUdp()));
thread.start();
return a.exec();
}