如何正确删除和终止 QThread [英] How to properly delete and terminate QThread

查看:218
本文介绍了如何正确删除和终止 QThread的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个继承自 QThread 的子类 MyClass.

I have got a subclass MyClass which inherits from QThread.

我像这样用 MainWindow 实例的父级创建它(这个):

I create it like this with a parent to the MainWindow instance (this):

mMyClass = new MyClass("some_value", 1, 5L, this);

我对 Qt 如何处理对象删除的理解是,当父对象被删除时,每个具有父对象的 QObject 都会被删除.

My understanding of how Qt deals with object deletion is that every QObject, which has a parent gets deleted when the parent gets deleted.

如果我的程序完成了,我会收到一个警告 QThread: Destroyed while thread is still running

If my program does finish I get a warning QThread: Destroyed while thread is still running

我该如何解决这个问题?我在 MainWindow 的解构器中使用以下代码进行了尝试.不幸的是它不能正常工作:

How can I fix this one up? I tried it with the following code in the deconstructor of MainWindow. Unfortunately it does not work properly:

if (mMyClass != 0 && mMyClass->isRunning()) {
    mMyClass->deleteLater();
    mMyClass->quit();
    mMyClass->wait();
}

推荐答案

您还没有指定您使用的 Qt 版本,所以我假设是 5.3.

You have not specified what version of Qt you use, so I'm supposing 5.3.

此外,我相信在您的线程代码中,您有某种形式的无限循环,如下所示:

Also, I believe in your thread code you have some form of infinite loop like the following:

while (1) {
    // do something here.
}

首先,最好是在线程创建后将线程deleteLater()槽连接到finished()信号:

First of all, the best is to connect the thread deleteLater() slot to the finished() signal after the creation of the thread:

mMyClass = new MyClass("some_value", 1, 5L, this);
connect(mMyClass, SIGNAL(finished()), mMyClass, SLOT(deleteLater()));

这将导致线程在线程完成其工作后尽快被其父线程删除.

This will cause the thread to be deleted by its parent as soon as possible after the thread finishes its job.

现在,为了完成这项工作,Qt 5.2 引入了方法 QThread::requestInterruption()QThread::isInterruptionRequested().您可以使用这些方法告诉您的线程以如下代码结束:

Now, to finish the job, Qt 5.2 introduced the methods QThread::requestInterruption() and QThread::isInterruptionRequested(). You can use these methods to tell your thread to finish with a code like this:

在您的主类退出代码中:

if (mMyClass != 0 && mMyClass->isRunning() ) {
    mMyClass->requestInterruption();
    mMyClass->wait();
}

在您的线程代码中:

while ( !this->isInterruptionRequested() ) {
    // do your job here!
}

将会发生的情况是,当关闭主窗口的代码被调用时,它会中断"线程(如果它有效并且正在运行).线程将检查它是否被中断并退出,触发 finished() 信号,这将触发 deleteLater() 槽,最后你的主窗口将删除在事件循环或班级清理中上课.

What will happen is that when the code that closes your main window is called, it will "interrupt" the thread (if it is valid and running). The thread will check if it has been interrupted and will exit, triggering the finished() signal, which will trigger the deleteLater() slot and finally your main window will delete the class either at the event loop or at the class clean up.

查看Qt 5.3 文档了解更多详情.

这篇关于如何正确删除和终止 QThread的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆