<QT编程篇>实现多线程的几种方式

目录

01 使用类Qthread

02 使用Qthread类的moveToThread方法

03 使用QThreadPool与QRunable

04 使用QtConcurrent

05 文章总结


大家好,这里是程序员杰克。一名平平无奇的嵌入式软件工程师。

杰克由于种种原因,需要自己编写上位机来与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_OBJECTpublic:    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>
qmakeQT += concurrent

使用方法:

  1. 在.pro文件中将该模块添加到工程:QT += concurrent

  2. 包含头文件#include <QtConcurrent>;

  3. 调用QTConcurrent(名词空间)提供的run()方法:QtConcurrent::run(函数名);

使用时:#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种的使用,需要根据实际应用工程,选择合适的多线程方式。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

杰克拉力船长

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值