Qt:在关闭期间线程仍在运行时,qthread被破坏 [英] Qt: qthread destroyed while thread is still running during closing
问题描述
我有一堂课
class centralDataPool : public QObject
{
Q_OBJECT
public:
centralDataPool(QObject * parent = 0);
~centralDataPool();
commMonitor commOverWatch;
private:
QThread monitorThread;
int totalNum;
signals:
void createMonitor(int);
};
在其构造函数中,我做到了:
In its constructor I did:
centralDataPool::centralDataPool(QObject* parent) : QObject(parent),totalNum(0)
{
connect(this, SIGNAL(createMonitor(int)), &commOverWatch, SLOT(createMonitor(int)));
commOverWatch.moveToThread(&monitorThread);
monitorThread.start();
}
当我调用此类的析构函数时,收到错误消息:
when I called the destructor of this class I get the error message:
qthread destroyed while thread is still running
但是当我试图在CentralDataPool类的析构函数中终止monitorThread时,
But when I tried to terminate the monitorThread in the destructor of class centralDataPool,
centralDataPool::~centralDataPool()
{
monitorThread.terminate();
}
我遇到内存泄漏.
在销毁其所有者对象期间终止线程的正确方法是什么?
What is the correct way to terminate a thread during the destruction of its owner object ?
推荐答案
您应注意,如果在线程的函数中运行循环,则应显式结束该循环,以正确终止线程.
You should note that if you have a loop running in a function of your thread, you should explicitly end it in order to properly terminate the thread.
您可以在类中名为finishThread
的成员变量,当应用程序将要关闭时,应将其设置为true
.只需提供一个插槽即可在其中设置finishThread
的值.当您要终止线程时,发出一个信号,该信号使用true
值连接到该插槽.设置为true
时,应在循环条件中提供finishThread
以结束该条件.之后,等待线程正常完成几秒钟,如果线程未完成,则强制其终止.
You can have a member variable in your class named finishThread
which should be set to true
when the application is going to close. Just provide a slot in which you set the value for finishThread
. When you want to terminate the thread emit a signal that is connected to that slot with a true
value. finishThread
should be provided in the loop condition to end it when it is set to true
. After that wait for the thread to finish properly for some seconds and force it to terminate if it did not finish.
因此您可以使用析构函数:
So you can have in your destructor :
emit setThreadFinished(true); //Tell the thread to finish
monitorThread->quit();
if(!monitorThread->wait(3000)) //Wait until it actually has terminated (max. 3 sec)
{
monitorThread->terminate(); //Thread didn't exit in time, probably deadlocked, terminate it!
monitorThread->wait(); //We have to wait again here!
}
这篇关于Qt:在关闭期间线程仍在运行时,qthread被破坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!