在关闭应用程序期间正确关闭线程,该线程可能会运行很长时间的循环
Properly closing a thread, that runs possible long for loops, during the closure of an application
所以,我有一个操作图像的类,即水平镜像或垂直镜像等。此类在其单独的线程中运行。
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())
,然后干净地结束计算/任务。这会增加开销,因此不应每纳秒检查一次。
相关文章:
- 为什么std::async使用同一个线程运行函数
- 如何在 qt 中从另一个线程运行 qt并发时关闭程序
- 如何使线程运行现有类的函数?C++
- 使用 4 个和 8 个线程运行时执行的时间相等
- 在我调用join()之前,std ::线程运行
- winsock连接调用崩溃如果多个线程运行,则在一个线程中正常工作
- 如何确保这部分代码仅由一个线程运行(在 openmp 中)
- 线程连接在另一个线程运行时会导致分段错误
- 动态提升线程运行存储在具有共享指针的向量中的对象的方法
- 如何启动一个 boost::线程运行一个成员函数
- 如果由另一个 OpenMP 程序调用,则外部调用的 OpenMP 程序仅使用一个线程运行
- 线程运行时间最少
- 计算线程运行的次数
- MySQL C API:从不同线程运行查询时出现分段错误
- 使用两个线程运行和中断一个无限循环
- 与icc 14一起使用多线程运行时库时的错误
- 为什么我得到无限循环只有线程# 0后,所有5个线程运行多线程c++用餐哲学家谜语
- 发布配置上的Visual Studio c++多线程运行时问题
- 使用逻辑线程运行程序
- 为什么设置 CPU 关联会使线程运行速度变慢