线程拒绝退出 [英] Thread refuses to quit

查看:171
本文介绍了线程拒绝退出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了 QThread :: currentThread() - > quit();

main.cpp:

#include <QCoreApplication>
#include <QtCore>
#include "myobject.h"

QThread* cThread;
MyObject* cObject;

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    cThread = new QThread();
    cObject = new MyObject();
    cObject->moveToThread(cThread);

    QObject::connect(cThread, SIGNAL(started()),
                     cObject, SLOT(doWork()));

    QObject::connect(cThread, SIGNAL(finished()),
                     cThread, SLOT(deleteLater()));

    QObject::connect(cThread, SIGNAL(finished()),
                     cObject, SLOT(deleteLater()));

    cThread->start();

    return a.exec();
}

myobject.cpp:

myobject.cpp:

#include "myobject.h"

MyObject::MyObject(QObject *parent) :
    QObject(parent)
{
}

void MyObject::doWork()
{
    qDebug() << "Hi";
    QThread::currentThread()->quit(); // It is supposed to stop here, but it doesn't.
    for (int i = 0; i < 1000000; i++) {
        qDebug() << i;
    }
}

myobject.h:

myobject.h:

#ifndef MYOBJECT_H
#define MYOBJECT_H

#include <QtCore>

class MyObject : public QObject
{
    Q_OBJECT
public:
    explicit MyObject(QObject *parent = 0);

signals:

public slots:
    void doWork();

};

#endif // MYOBJECT_H

它应该停在myobject。 cpp与 QThread :: currentThread() - > quit(); 但不是。

It is supposed to stop in myobject.cpp with QThread::currentThread()->quit(); but it doesn't.

一个错误说这个问题太短了。

Getting an error saying that this question is too short.

解决方案:添加return;

Solution: add "return;" after the quit call.

推荐答案

函数退出的文档(这是退出调用):

From the documentation of the function exit (which is what quit calls):


注意,与同名的C库函数不同,这个
函数返回调用者 -
停止的事件处理

Note that unlike the C library function of the same name, this function does return to the caller -- it is event processing that stops

这意味着你写的代码是循环进行的。您正在停止执行线程的事件循环,这是 唯一的事情。该线程将完成 doWork()的执行。

Which means the code you wrote is behaving as it should by going into the loop. You are stopping the event loop of the thread from executing, and that's the only thing quit does. The thread will finish the execution of doWork().

现在引发一个有趣的问题:will cThread cObject 被删除?不会。当删除时,会删除具有 deleteLater 的对象控制返回到事件循环。但是这里你只是停止了线程的事件循环,所以即使 deleteLater 被发布,它们也不会被处理。

Now it raises an interesting question : will cThread and cObject be deleted? No. An object with deleteLater will be deleted when the control returns to the event loop. But here you just stopped the event loop of the thread, so even if the deleteLater are posted they will not be processed.

生存,你会有内存泄漏。一个简单的测试是为 MyObject 声明一个虚拟析构函数,它只打印一些东西并检查是否被调用。

Your object will survive and you will have a memory leak. An easy test will be to declare a dummy destructor for MyObject which just prints something and check if it is called.

这篇关于线程拒绝退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆