Qt多线程如何在关闭窗口时正确退出

当我们在跑非常耗时的多线程任务时,如果用户点击了关闭主窗口按钮,此时不处理的话,它虽然关闭了主窗口,但是程序其实会一直在跑的,还没有真正退出的,在任务管理器里还可以看到它,而且在debug窗口也会看到还在跑。

怎么办?

解决方法:
1、 窗口头文件中定义
public:
QThread thread;
Worker *ycthd;
实现文件 窗口构造函数添加::
this->setAttribute(Qt::WA_DeleteOnClose,true);
ycthd = new YcThread();
ycthd->moveToThread(&thread);
thread.start();
thread.setPriority(QThread::HighestPriority);
connect(this,&ABC::beginsignal,ycthd,&Worker ::beginslot);
connect(&thread, &QThread::finished, ycthd, &QObject::deleteLater);

2、窗口析构函数添加:
ycthd->isRun = false; //设置这个标志位,如果多线程还在跑,在跑的过程中判断这个值,false就退出循环
thread.quit();
thread.wait();//要阻塞等待线程完全跑完退出,不然delete会报错
//关闭窗口一阵子,就可以看到Worker 析构函数执行了,表明已经退出线程

3、开始计算的时候:
ycthd->isRun = true; //这个标志位允许程序持续跑
emit test();

结论:
1、不能用 this->thread->terminate(); 来终止线程,程序会挂掉。
2、多线程其实就是它在等待信号槽过来,有信号就启动运行槽函数,运行完就继续等待,啥也不帮你干。
3、当它啥也不干的时候,才可以安全退出它。
4、它没那么复杂,也不难理解,就像老板让一个工人帮他做事的时间里,你不能命令工人出去工厂外面休息,要让工人停止干活,你必须跟老板报告下,让老板不再让工人干他的事才行;当工人做完老板的事没活干了,你才能命令他出去工厂外面休息。

  • 5
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
在使用 Qt 进行多线程渲染,可以使用 QtQThread 类来创建多个线程,然后在每个线程中执行渲染任务。但是,由于 Qt 的 GUI 线程不是线程安全的,因此需要使用信号和槽机制来进行线程间通信。 在使用 OpenSceneGraph 进行渲染,可以使用 osgViewer::Viewer 类来创建视图窗口,并在其中添加多个场景。然后,可以使用 osgViewer::Viewer::frame() 函数在每个线程中循环渲染每个场景。 下面是一个简单的示例代码: ```cpp #include <QThread> #include <osgViewer/Viewer> class RenderThread : public QThread { public: RenderThread(osgViewer::Viewer* viewer) : _viewer(viewer) {} private: void run() override { while (!isInterruptionRequested()) { _viewer->frame(); } } osgViewer::Viewer* _viewer; }; int main(int argc, char** argv) { osgViewer::Viewer viewer; viewer.setSceneData(createSceneGraph()); viewer.setUpViewInWindow(100, 100, 800, 600); RenderThread thread1(&viewer); RenderThread thread2(&viewer); thread1.start(); thread2.start(); int ret = QApplication(argc, argv).exec(); thread1.requestInterruption(); thread2.requestInterruption(); thread1.wait(); thread2.wait(); return ret; } ``` 在上面的示例代码中,我们创建了两个 RenderThread 线程,并将 osgViewer::Viewer 对象传递给它们。然后,在每个 RenderThread 线程中,我们使用 while 循环调用 osgViewer::Viewer::frame() 函数来不断渲染场景。最后,在主线程中启动 QApplication 并等待 RenderThread 线程退出。 需要注意的是,上面的示例代码只是一个简单的示例,并没有考虑线程安全和线程同步的问题。在实际应用中,需要根据具体情况进行更加完善的设计。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

XINGTECODE

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值