QThread跟随父对象自动退出
QThread自动退出
- 通过继承QThread类,重写
void run()
函数; - 将耗时操作放入run函数,在子线程中执行;
- 设置Worker实例父对象;
- 父对象退出后,Worker实例析构,子线程自动退出;
实现代码
Worker.h
#ifndef WORKER_H
#define WORKER_H
#include <QThread>
class Worker : public QThread
{
Q_OBJECT
public:
explicit Worker(QObject *parent = nullptr);
~Worker();
void run();
};
#endif // WORKER_H
Worker.cpp
#include "worker.h"
#include <QtCore>
Worker::Worker(QObject *parent)
: QThread(parent)
{
qDebug() << "Worker Thread:" << QThread::currentThreadId();
}
Worker::~Worker()
{
qDebug() << "~Worker Thread:" << QThread::currentThreadId();
/* 请求中止 */
requestInterruption();
/* 退出线程 */
quit();
/* 等待线程退出 */
wait();
}
void Worker::run()
{
qDebug() << "Worker Run Thread:" << QThread::currentThreadId();
/* 是否请求中止 */
while (!isInterruptionRequested())
{
QThread::sleep(1);
qDebug() << "Hello world!";
}
}
MainWindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
MainWindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QtWidgets>
#include "worker.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
qDebug() << "Main Thread:" << QThread::currentThreadId();
/* 当前窗口退出后,Worker线程自动退出 */
Worker* worker = new Worker(this);
worker->start();
}
MainWindow::~MainWindow()
{
delete ui;
}
打印结果
Main Thread: 0x10eaa9dc0
Worker Thread: 0x10eaa9dc0
Worker Run Thread: 0x7000027ba000
Hello world!
Hello world!
Hello world!
~Worker Thread: 0x10eaa9dc0
Hello world!