Qt应用开发(进阶篇)——线程 QThread

一、前言

        QThread类继承于QObject基类,是Qt经典基础工具类,QThread类提供了一种独立于平台的方式来管理线程,让开发者能够快速的完成多线程的创建和使用。

        正常情况下,一个PC程序使用到多线程的概率是非常高的,在不同方式的通讯场景使用、在耗时任务中使用、在独立的任务中使用等等。所以学习好多线程的使用是非常重要的,这也是程序员必备的技能之一。在C++中也有线程的功能,但是Qt提供的QThread线程,更适用于在Qt框架中使用。

        QThread对象管理一个独立的线程,调用start()启用,启用成功触发started()信号,当线程结束的时候触发finished()信号,并提供isFinished()、isRunning()查询状态。使用exit()quit()主动退出线程,wait()阻塞等待线程结束。

        QThread线程还可以使用setPriority()设置优先级,而优先级参数的效果取决于操作系统的调度策略,在一些不支持线程优先的操作系统,比如Linux,优先级将被忽略。

二、创建线程方法一

        QThreads在run()中开始执行,默认情况下,run()通过调用exec()启动事件循环,并在线程内运行Qt事件循环,当run函数执行完成的时候,线程执行结束触发信号并退出。

        所以创建线程的第一种方式就是继承QThread,重新实现run函数。

#ifndef MYTHREAD_H
#define MYTHREAD_H

#include <QThread>
#include <QObject>

class MyThread : public QThread
{
    Q_OBJECT
public:
    explicit MyThread(QObject *parent = nullptr);
    ~MyThread();
protected:
    virtual void run();
Q_SIGNALS:
    void printMsg(int);
};

#endif // MYTHREAD_H
#include "mythread.h"
#include <QDebug>
MyThread::MyThread(QObject *parent) : QThread(parent)
{

}
MyThread::~MyThread()
{
    qDebug()<<"~MyThread ";
}
void MyThread::run()
{
    qDebug()<<"MyThread "<<this->currentThreadId();
    for(int i = 0 ; i < 5 ;i++)
    {
        qDebug()<<i;
        emit printMsg(i*2);
    }
}
qDebug()<<"main thread id"<<QThread::currentThreadId();
thread = new MyThread(this);
thread->start();
connect(thread,&MyThread::finished,this,[](){
    qDebug()<<"thread finish";
});
connect(thread,&MyThread::printMsg,this,[](int num){
    qDebug()<<"thread Msg "<<num;
});

        在上面的例子中,我们继承QThread,重新实现Run函数,在线程中打印数字,并且抛出自定义的信号printMsg,主线程绑定信号打印信息。线程结束后QThread会触发finished信号,我们也绑定该信号打印信息,当主程序结束后,线程类调用析构函数并打印信息。

main thread id 0x7ffb77158040
MyThread  0x7ffb47767700
0
1
2
3
4
thread Msg  0
thread Msg  2
thread Msg  4
thread Msg  6
thread Msg  8
thread finish
~MyThread 

        但是打印的结果并不是我们想要的,因为我们打印数字的同时一边在抛出信号,为什么会打印结束了,才开始执行槽函数呢,并没有两边交替打印,这是因为信号槽的连接方式默认为Qt::AutoConnection,而如果是线程之间的连接,会自动转换成Qt::QueuedConnection(当控制返回到接收者线程的事件循环时调用该槽,槽在接收者的线程中执行)。所以我们需要修改连接方式。

connect(thread,&MyThread::printMsg,this,[](int num){
     qDebug()<<"thread Msg "<<num;
},Qt::DirectConnection);
main thread id 0x7f2e6825d040
MyThread  0x7f2e38a32700
0
thread Msg  0
1
thread Msg  2
2
thread Msg  4
3
thread Msg  6
4
thread Msg  8
thread finish
~MyThread 

二、创建线程方法二

        使用QObject::moveToThread()将工作对象移动到线程中,是Qt线程使用的第二种方式。

#ifndef WORKER_H
#define WORKER_H

#include <QObject>
#include <QDebug>
#include <QThread>
class worker : public QObject
{
    Q_OBJECT
public:
    explicit worker(QObject *parent = nullptr);
Q_SIGNALS:
    void resultReady(QString result);
public Q_SLOTS:
    void doWork(QString parameter);
};

#endif // WORKER_H
#include "worker.h"

worker::worker(QObject *parent) : QObject(parent)
{

}
void worker::doWork(QString parameter) {
    qDebug()<<QThread::currentThreadId();
    QString result;
    qDebug()<<"work doWork"<<parameter;
    emit resultReady(result);
}

        定义完工作类,我们要定义一个线程,并使用moveToThread把工作类“移动”到线程中。

class MainWindow : public QMainWindow
{
    Q_OBJECT
public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();
Q_SIGNALS:
    void doWork(QString);
private slots:
    void on_pushButton_clicked();

private:
    QThread *m_thread;
    worker *m_work;
};
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    m_thread = new QThread(this);
    m_work = new worker();
    m_work->moveToThread(m_thread);
    connect(this,&MainWindow::doWork,m_work,&worker::doWork);
    connect(m_work,&worker::resultReady,this,[&](QString result){
        qDebug()<<"recv m_work Msg "<<result;
    });
    m_thread->start();
}
void MainWindow::on_pushButton_clicked()
{
    qDebug()<<"main thread id"<<QThread::currentThreadId();
    emit doWork("hello world");
}

         执行结果:

main thread id 0x7f016253c040
0x7f013bfff700
work doWork "hello world"
recv m_work Msg  ""

三、线程使用注意事项

1、CPU飙升

        初次使用QThread的同学,经常会出现一个问题,在线程执行的函数体中,使用死循环一直读串口或者后台等一些数据信息,读到信息抛出信号,读不到一直调用自定义读取的函数。在这种工况下,如果读取的函数是非阻塞的,那么整个CPU的资源都被子线程占用着,系统没办法合理的分配时间片。所以如果有需要使用读取线程并且用死循环读取信息的同学,一定要确保读取的函数是阻塞的或者做sleep操作。

2、阻塞线程退出异常

        正常情况下,读取线程我们会定义一个变量,用来控制死循环的结束兼线程的结束。

bool m_loop;
void MyThread::run()
{
    qDebug()<<"MyThread "<<this->currentThreadId();
    m_loop = true;
    while (m_loop) {
        qDebug()<<10;
        sleep(1);
    }
}
void MyThread::stop()
{
    m_loop = false;
}
thread->stop();

        在上面的实例中,我们使用m_loop变量来结束死循环,让run函数结束,从而控制线程的结束。

        但是如果是阻塞的场景下,这样的逻辑就不够用了。直接退出会报“QThread: Destroyed while thread is still running”。

        因为死循环中,读取函数一直卡着,这样就没办法退出,这时候我们需要注意阻塞的退出方法,比如waitForReadyRead默认为3秒、linux中的select设置超时、socketcan使用阻塞则用关闭退出等等。配合使用QThread的wait函数,会阻塞在该函数等待线程的退出,让主线程退出子线程的时候做出等待的操作。

thread->stop();
thread->quit();
thread->wait();

3、moveToThread方式的线程退出

        使用此方式进行创建线程,它不像重写run一样,run函数结束线程就自动退出。我们一开始调用的是start,在程序中它一直都处于运行的状态,只是如果你没有使用信号触发,它会处于休眠状态。所以在程序结束的时候记得使用quit和wait退出线程,是否会报“QThread: Destroyed while thread is still running”。

thread->quit();
thread->wait();

4、moveToThread方式的工作类不能有父类

        在第二例子中,在定义worker类的时候,不能写成:

m_work = new worker(this);

        否则会有告警:

QObject::moveToThread: Cannot move objects with a parent

        并且运行之后发现,work的函数调用其实是在主线程中,并没有在子线程中执行。

main thread id 0x7f5299998040
0x7f5299998040
work doWork "hello world"
recv m_work Msg  ""

5、线程中使用成员类异常告警

        问题代码如下:

#ifndef MYTHREAD_H
#define MYTHREAD_H

#include <QThread>
#include <QObject>
#include <QTimer>
class MyThread : public QThread
{
    Q_OBJECT
public:
    explicit MyThread(QObject *parent = nullptr);
    ~MyThread();
    void stop();
protected:
    virtual void run();
Q_SIGNALS:
    void printMsg(int);
private:
    QTimer *m_timer;
    bool m_loop;
};

#endif // MYTHREAD_H
#include "mythread.h"
#include <QDebug>
MyThread::MyThread(QObject *parent) : QThread(parent)
{
    m_timer = new QTimer(this);
    connect(m_timer,&QTimer::timeout,this,[]()
    {
        qDebug()<<"time out";
    });
}
MyThread::~MyThread()
{
    qDebug()<<"~MyThread ";
}
void MyThread::run()
{
    qDebug()<<"MyThread "<<this->currentThreadId();
    m_loop = true;
    m_timer->start(1000);
    while (m_loop) {
        qDebug()<<10;
        sleep(1);
    }
}
void MyThread::stop()
{
    m_loop = false;
}

        在上面的例子中,MyThread成员类变量QTimer,在构造函数中实例化,在run函数中启动,这时候线程启动的时候会报异常:

QObject::startTimer: Timers cannot be started from another thread

        这是因为在重写run的这种方式中,除了run函数内其他函数包括类都是属于主线程的,包括构造函数。所以定时器是属于主线程的类,在子线程中控制它,就会告警,于是我们修改定时器定义:

void MyThread::run()
{
    qDebug()<<"MyThread "<<this->currentThreadId();
    m_loop = true;
    m_timer = new QTimer(this);
    connect(m_timer,&QTimer::timeout,this,[]()
    {
        qDebug()<<"time out";
    });
    m_timer->start(1000);
    while (m_loop) {
        qDebug()<<10;
        sleep(1);
    }
}

        这时候又会报另一个错误,不能在子线程中为主线程的类创建子类。

QObject: Cannot create children for a parent that is in a different thread.
(Parent is MyThread(0x561d014478b0), parent's thread is QThread(0x561d01438e20), current thread is MyThread(0x561d014478b0)

        所以我们需要去掉this指针,就不会有这个错误,这时候需要注意指针的释放,因为我们没有定义父类,它不会跟随父类的释放而释放。

void MyThread::run()
{
    qDebug()<<"MyThread "<<this->currentThreadId();
    m_loop = true;
    QTimer *m_timer = new QTimer();
    connect(m_timer,&QTimer::timeout,this,[]()
    {
        qDebug()<<"time out";
    });
    m_timer->start(1000);
    while (m_loop) {
        qDebug()<<10;
        sleep(1);
    }
}
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

波塞冬~

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

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

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

打赏作者

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

抵扣说明:

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

余额充值