之前在项目中用到了Qt的多线程,
因为以前用的一直是用一个类直接继承QThread,然后再重写run()方法。
需要注意的是:
QThread只有run函数是在新线程里的,其他所有函数都在QThread生成的线程里。
后来查阅了一些资料才知道,
Qt有两种多线程的方法,其中一种是继承QThread的run函数,
另外一种是把一个继承于QObject的类用moveToThread函数转移到一个Thread里。
Qt4.8之前都是使用继承QThread的run这种方法,但是Qt4.8之后,Qt官方建议使用第二种方法。
下面记录一下moveToThread()的简单用法,防止遗忘:
1:定义一个继承于QObject的类A
2:然后用这个类的一个实例a调用moveToThread(),将QThread的一个实例thread的指针传进moveToThread()
a.moveToThread(&thread);
3:然后启动线程,thread.start()
4:把要处理的事务放在process函数中,再利用connect,线程一启动的话就会运行process函数
connect(&thread, &QThread::started, &a, &A::process);
为了方便管理线程,这里最好再写一个管理线程的类,代码如下:
#ifndef AUXCONTROLLER_H
#define AUXCONTROLLER_H
#include "auxThreadMotor.h"
#include "auxThreadMPU.h"
class auxThreadController : public QObject
{
Q_OBJECT
public:
auxThreadController()
{
motor.moveToThread(&motorThread);
mpu.moveToThread(&MPUThread);
//启动线程
motorThread.start();
MPUThread.start();
connect(&motorThread, &QThread::started, &motor, &auxThreadMotor::process);
connect(&MPUThread, &QThread::started, &mpu, &auxThreadMPU::process);
//该线程结束时销毁
connect(&motorThread, &QThread::finished, &motor, &QObject::deleteLater);
connect(&MPUThread, &QThread::finished, &mpu, &QObject::deleteLater);
}
//析构函数中调用quit()函数结束线程
~auxThreadController()
{
motorThread.quit();
motorThread.wait();
MPUThread.quit();
MPUThread.wait();
}
private:
QThread motorThread;
QThread MPUThread;
auxThreadMotor motor;
auxThreadMPU mpu;
};
#endif // !AUXCONTROLLER_H
使用的时候直接在main函数里实例化auxThreadController的一个对象即可。