Qt多线程编程两种方式详解

QT的多线程编程主要有两种方式:

第一种是继承自QThread,然后重写run()函数;

第二种是继承自QObject,然后把整个对象moveToThread;

两种方法比较:

第一种方法只有run()函数是运行在子线程中。如果在构造函数中调用其他方法,则该方法运行在主线程中;如果在run()函数中调用其他方法,则该方法运行在子线程中。

第二种方法整个对象都移入到一个子线程中,然后通过信号槽进行通信,该对象的所有槽函数都会在子线程中执行。如果在构造函数中调用其他方法,则该方法运行在主线程中;如果在槽函数函数中调用其他方法,则该方法运行在子线程中。

下面通过实例来介绍它们的使用:

第一种方法:

file_in.h

#ifndef FILE_IN_H
#define FILE_IN_H

#include <QThread>
#include <QDebug>

class File_in : public QThread
{
    Q_OBJECT
public:
    File_in(QObject *parent = 0);

protected:
    void run();
    void do_something();
};

#endif // FILE_IN_H

file_in.cpp

#include "file_in.h"

File_in::File_in(QObject *parent):
    QThread(parent)
{
    qDebug()<<"file_in 构造函数"<<QThread::currentThreadId();
}

void File_in::run()
{
    qDebug()<<"file_in run()函数"<<QThread::currentThreadId();
    do_something();
}

void File_in::do_something()
{
    qDebug()<<"file_in do_something()函数"<<QThread::currentThreadId();
}

从上面的运行可以看出run()函数与主线程不在同一个线程中,在run()函数中调用相应的方法,那这个方法也会在子线程中运行。

QT开发交流+赀料君羊:714620761

第二种方法:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QThread *thread = new QThread;
    moveThread *movethread = new moveThread;
    movethread->moveToThread(thread);
    connect(thread,SIGNAL(started()),movethread,SLOT(test()));
    thread->start();

    qDebug()<<"mainwindow构造函数"<<QThread::currentThreadId();
}

先创建一个线程,然后把想要移入到子线程中运行的对象moveToThread就行了,然后该对象的所有槽函数就都会在子线程中运行了。

原文链接:,转发请注明来源!