目录
大家好,这里是程序员杰克。一名平平无奇的嵌入式软件工程师。
杰克由于种种原因,需要自己编写上位机来与MPSOC的嵌入式软件进行联调。使用QT编写了该上位机软件,由于项目第一阶段进度接近收尾,便在空闲时间把一些内容记录分享出来。本篇推送主要是介绍一下QT中实现多线程的几种方式:
-
使用类QThread
-
使用Qthread类的moveToThread方法
-
使用QthreadPool与QRunable
-
使用QtConcurrent
01 使用类Qthread
声明一个类,继承Qthread类,然后重写Run()方法;使用时new关键字生成对应的类对象,调用start()方法.
#include <QThread>
声明时:
class runThread: public QThread
{
Q_OBJECT
void run() override {
/* ... here is the expensive or blocking operation ... */
}
};
......
使用时:
runThread runWorker = new runThread(this);
runWorker->start();
02 使用Qthread类的moveToThread方法
声明一个类,继承QObject类,通过信号与信号槽的方式实现多线程。使用时:实现一个该类的对象以及QThread类的对象,然后调用movetothread()方法;最后调用QThread类对象的start()方法,启动线程;
#include <QObject>
声明时:
class moveThread : public QObject
{
Q_OBJECT
public:
explicit moveThread(QObject *parent = nullptr);
......
};
......
使用时:
class Controller : public QObject
{
Q_OBJECT
QThread workerThread;
public:
Controller() {
moveThread *runWorker = new moveThread;
worker->moveToThread(&workerThread);
connect(&workerThread, &QThread::finished, worker, &QObject::deleteLater);
workerThread.start();
}
~Controller() {
workerThread.quit();
workerThread.wait();
}
public slots:
};
03 使用QThreadPool与QRunable
声明一个类,继承QRunnable类,然后重写Run()方法;使用时声明一个该类的对象,通过QThreadPool(线程类)的静态方法QThreadPool::globalInstance()获取全局的线程池,然后调用start()方法启动该类,让该类的Run()方法在另外一个线程执行;
#include <QRunnable>
声明时:
class poolrunnablethread : public QRunnable
{
public:
explicit poolrunnablethread();
protected:
void run() override {
/* ... here is the expensive or blocking operation ... */
}
......
};
......
使用时:
poolrunnablethread runnableWorker;
QThreadPool::globalInstance()->start(&runnableWorker);
04 使用QtConcurrent
QT Concurrent作为一个模块,其支持并发执行编程代码。在QTConcurrent(名词空间)提供了高级的API,可以在不使用低级线程原语的情况下编写多线程程序。使用时调用QTConcurrent(名词空间)提供的run()方法,将需要处理的逻辑丢到另外一个线程中执行。
QtConcurrent Namespace | |
头文件 | #include <QtConcurrent> |
qmake | QT += concurrent |
使用方法:
|
使用时:
#include <QtConcurrent>
#include <QThread>
void funcOne()
{
qDebug() << "funcOne Thread ID:" << QThread::currentThreadId();
}
QtConcurrent::run(funcOne);
QtConcurrent::run([=]()
{
qDebug() << "funTwo Thread ID:" << QThread::currentThreadId();
});
05 文章总结
QT中实现多线程的方法有很多种,本文将描述了常用的4种方式。对于4种的使用,需要根据实际应用工程,选择合适的多线程方式。