Qt:qthread 在关闭期间线程仍然 运行 时被销毁

Qt: qthread destroyed while thread is still running during closing

我有一个 class:

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

当我调用此 class 的析构函数时,我收到错误消息:

qthread destroyed while thread is still running

但是当我试图在 class centralDataPool 的析构函数中终止 monitorThread 时,

centralDataPool::~centralDataPool()
{
    monitorThread.terminate();
}

我遇到内存泄漏问题。

在销毁所有者对象期间终止线程的正确方法是什么?

您应该注意,如果您的线程函数中有一个循环 运行,您应该显式结束它以便正确终止线程。

您可以在 class 中有一个名为 finishThread 的成员变量,当应用程序将要关闭时,应将其设置为 true。只需提供一个插槽,您可以在其中设置 finishThread 的值。当您想终止线程时,会发出一个信号,该信号连接到具有 true 值的插槽。当设置为true时,循环条件中应提供finishThread以结束循环。之后等待线程正确完成几秒钟,如果没有完成则强制终止。

所以你可以在你的析构函数中:

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!
}