在 运行 中间删除 Qthread

Deleting Qthread on the middle of running

我用classA创建了一个线程,删除classA后线程没有被删除。它继续 运行.

我显式调用了线程析构函数、退出和退出函数,但线程仍然没有停止 运行。

有没有类似KILL函数的东西可以停止线程执行

void A::init()
{
    WorkerThread *Thread = new WorkerThread(this);
}

void B::slotClose()
{
    A *obj = getObj();
    if(obj)
    {
    m_pScene->removeItem(obj);
    obj->deleteLater(); // this calls thread distructor also but thread execution is not stopping
    }
}

来自文档:

Note that deleting a QThread object will not stop the execution of the thread it manages. Deleting a running QThread (i.e. isFinished() returns false) will result in a program crash. Wait for the finished() signal before deleting the QThread.

永远不要删除 运行 QThread 对象。

所以我认为最好在您的 WorkerThread 中编写一些 termination/quitting 逻辑,公开一些插槽,例如 quit 并将信号与此 quit 插槽连接。

如果你只是想无论如何终止线程,只需连接销毁的SIGNAL来终止SLOT(http://doc.qt.io/qt-5/qthread.html#terminate)

所以假设你的 A class 派生自 QObject,你会在这个 class 中做什么是:

connect(this, SIGNAL(destroyed()), Thread, terminate());

如果您有自己的插槽 quit 暴露,那么您要确保正确停止循环中正在执行的所有操作,而不是 terminate() 使用 quit().

connect(this, SIGNAL(destroyed()), Thread, quit());

下面是实现这种逻辑的示例:http://blog.debao.me/2013/08/how-to-use-qthread-in-the-right-way-part-1/

或者只是将 quit = true 放入您的 ThreadWorker 析构函数中。

应该很简单。祝你好运!

还有一些带有示例的官方文档(imo 做对了):

https://wiki.qt.io/QThreads_general_usage

https://doc.qt.io/archives/qt-5.8/qtnetwork-blockingfortuneclient-example.html

https://doc.qt.io/archives/qt-5.8/qtcore-threads-mandelbrot-example.html