我有一个有很多线程的应用程序,当我关闭我的主应用程序并调用线程析构函数进行必要的清理时,我想退出这些线程。
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?发布于 2014-04-24 20:46:43
发布于 2014-04-24 21:36:39
在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();https://stackoverflow.com/questions/23268331
复制相似问题