Nya*_*uko 8 c++ qt multithreading qthread
我有一节课:
class centralDataPool : public QObject
{
Q_OBJECT
public:
centralDataPool(QObject * parent = 0);
~centralDataPool();
commMonitor commOverWatch;
private:
QThread monitorThread;
int totalNum;
signals:
void createMonitor(int);
};
Run Code Online (Sandbox Code Playgroud)
在它的构造函数中我做了:
centralDataPool::centralDataPool(QObject* parent) : QObject(parent),totalNum(0)
{
connect(this, SIGNAL(createMonitor(int)), &commOverWatch, SLOT(createMonitor(int)));
commOverWatch.moveToThread(&monitorThread);
monitorThread.start();
}
Run Code Online (Sandbox Code Playgroud)
当我调用此类的析构函数时,我收到错误消息:
qthread destroyed while thread is still running
Run Code Online (Sandbox Code Playgroud)
但是当我试图在类centralDataPool的析构函数中终止monitorThread时,
centralDataPool::~centralDataPool()
{
monitorThread.terminate();
}
Run Code Online (Sandbox Code Playgroud)
我得到内存泄漏.
在销毁其所有者对象期间终止线程的正确方法是什么?
Nej*_*jat 13
您应该注意,如果您在线程的函数中运行循环,则应该显式结束它以正确终止线程.
您可以在类中指定一个成员变量,该变量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!
}
Run Code Online (Sandbox Code Playgroud)