繁体   English   中英

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);
};

在它的构造函数中我做了:

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的类中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!
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM