我有一堂课:
class centralDataPool : public QObject
{
Q_OBJECT
public:
centralDataPool(QObject * parent = 0);
~centralDataPool();
commMonitor commOverWatch;
private:
QThread monitorThread;
int totalNum;
signals:
void createMonitor(int);
};
在其构造函数中,我做到了:
centralDataPool::centralDataPool(QObject* parent) : QObject(parent),totalNum(0)
{
connect(this, SIGNAL(createMonitor(int)), &commOverWatch, SLOT(createMonitor(int)));
commOverWatch.moveToThread(&monitorThread);
monitorThread.start();
}
当我调用此类的析构函数时,收到错误消息:
qthread destroyed while thread is still running
但是,当我尝试在CentralDataPool类的析构函数中终止monitorThread时,
centralDataPool::~centralDataPool()
{
monitorThread.terminate();
}
我收到内存泄漏。
在销毁其所有者对象期间终止线程的正确方法是什么?
您应注意,如果在线程的函数中运行循环,则应显式结束该循环,以正确终止线程。
您可以在类中具有一个成员变量,该成员变量的名称finishThread
应true
在应用程序将要关闭时设置为。只需提供一个用于设置值的插槽即可finishThread
。当您要终止线程时,发出一个与true
值连接到该插槽的信号。finishThread
设置为时,应在循环条件中提供该条件以使其终止true
。之后,等待线程正常完成几秒钟,如果线程未完成,则强制其终止。
因此,您可以使用析构函数:
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!
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句