我有一个应用程序。我想在关闭主应用程序并调用线程驱动器以使必要性清理时退出线程。
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?
QThread::wait
以确保线程在终止应用程序之前优雅结束。
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();