[英]The correct way to exit a thread in Qt with finished signal and make clean_up
我有一個有很多線程的應用程序。我想在關閉主應用程序時退出線程並調用線程析構函數來進行必要的清理。
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?
在您的 run 函數中,while 循環將導致您的線程永遠不會停止,除非您自己管理線程終止,例如:
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() 和 OnFinished() 槽中完成。
在類的析構函數中添加:
th->quit();
th->wait();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.