正确的方法是通过完成信号在QT中退出线程并制作Clean_up

问题描述 投票:0回答:2

我有一个应用程序。我想在关闭主应用程序并调用线程驱动器以使必要性清理时退出线程。

Class Thread :public QThread{ Thread(); run(){ while(1){ //do work } } ~Thread(){ //want to make clean up } }; Class my_app :public QCoreapplication{ my_app(){ Thread th1; connect(&th1,SIGNAL(finished()),&th1,deleteLater()); connect(&th1,SIGNAL(finished()),&th1,quit()); } }; //And my th1 thread runs in while.So I know that is the problem it runs on while and never emits the finished signal //How can be achievable?
    
c++ c multithreading qt
2个回答
2
投票
  1. 没有子类Qthread.
  2. 工人循环提供一些线程安全的标志,这将表明工人应结束工作。
  3. 在终止应用程序之前,您应该致电
  4. QThread::wait
    以确保线程在终止应用程序之前优雅结束。
    
在您的运行函数中,while循环将导致线程永远不会停止,除非您自行管理线程终止:

1
投票
Class Thread :public QThread{ Thread(); protected: void run() { while(1) { if(this->finishThread==true) return; } } private: bool finishThread; }

您最好从qobject得出类并使用movetothread。您可以在班级的构造函数中执行此操作:

th = new QThread();

this->setParent(0);
this->moveToThread(th);
clientSocket.moveToThread(th);

QObject::connect(th,SIGNAL(started()),this,SLOT(OnStarted()));
QObject::connect(th,SIGNAL(finished()),this,SLOT(OnFinished()));

th->start();
您的初始化和终止任务应分别在onstarted()和onfined()插槽中完成。

在您的班级的破坏者中添加以下添加:

th->quit();
th->wait();

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.