在关闭应用程序期间正确关闭线程,该线程可能会运行很长时间的循环

Properly closing a thread, that runs possible long for loops, during the closure of an application

本文关键字:线程 运行 长时间 循环 应用程序      更新时间:2023-10-16

所以,我有一个操作图像的类,即水平镜像或垂直镜像等。此类在其单独的线程中运行。

m_imageMirrorer = new ImageMirrorer();
m_imageMirrorer->moveToThread(&m_thread);
m_thread.start();
connect(&m_thread, &QThread::finished, this, &QObject::deleteLater);

现在,为了在用户随机关闭应用程序时正确关闭线程,我在析构函数中添加了以下代码。

    m_thread.quit();
    if(!m_thread.wait(3000)) //Wait until it actually has terminated (max. 3 sec)
    {
        m_thread.terminate(); //Thread didn't exit in time, probably deadlocked, terminate it!
        m_thread.wait(); //We have to wait again here!
    }
    if(m_imageMirrorer)
    {
        delete m_imageMirrorer;
    }

实际上,我最初尝试在析构函数中根本没有使用quit()wait()terminate() m_thread。但后来它总是给出错误QThread: Destroyed while thread is still running. deleteLater没有采取任何措施来避免那次特定的崩溃。

我现在做得对吗?

谢谢。

本质上,你会用原子来做这种任务。然而,Qt已经集成了一个机制来做到这一点。

https://doc.qt.io/qt-5/qthread.html#isInterruptionRequested 由请求中断触发。

在运行任务时,您可以集成检查if (QThread::currentThread()->isInterruptionRequested()),然后干净地结束计算/任务。这会增加开销,因此不应每纳秒检查一次。