Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ Qt:qthread在关闭期间线程仍在运行时被销毁_C++_Multithreading_Qt_Qthread - Fatal编程技术网

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

C++ Qt:qthread在关闭期间线程仍在运行时被销毁,c++,multithreading,qt,qthread,C++,Multithreading,Qt,Qthread,我有一门课: class centralDataPool : public QObject { Q_OBJECT public: centralDataPool(QObject * parent = 0); ~centralDataPool(); commMonitor commOverWatch; private: QThread monitorThread; int totalNum; signals: void createMon

我有一门课:

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
值连接到该插槽<当循环条件设置为
true
时,应在循环条件中提供code>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!
}

你的析构函数代码在哪里?@ViníciusGobboA.deOliveira查看编辑。你不应该完成这样的线程。请看文档:@ViníciusGobboA.deOliveira,您好,我尝试添加wait()或切换到quit(),但都不起作用……您能给我更多提示吗?哦!我错过了。它是一个受静态保护的方法,因此不从
QThread
继承就无法调用它。在这种情况下,您必须以某种方式向线程中正在执行的方法发出信号,表示它必须结束。不管怎样,这是最正确的方法来做到这一点而不泄漏。我可以通过这种方式调用析构函数吗?删除对象;object.deleteLAter();对象->~Class();