关于c ++:在调用exit()quit()或终止()之后Qt线程执行不会停止

Qt thread execution does not stop after exit() quit() or terminate() was called

首先,我已经阅读了QThreads并使用了QEventLoop,但是我不确定我的实现是否正确。

TL; DR参见下面的"问题详细信息"。

最有用的信息来源是Qt Wiki,KDAB Qthread演示文稿(用于w / w和o / o事件循环),此处和此处与该问题相关的SO帖子。

我的情况是:

我有一个可能运行很长时间的功能,具有多个I / O磁盘调用。因此,我需要一个线程来不阻止UI。为此,我实现了自己的线程实现。

TL; DR QThreads

我的理解是QThread是一个单独的事件循环对象,并且需要自定义run()实现或将对象移动到新创建的线程对象中,其中移动的对象可以生存(并运行)。我所描述的是带有事件循环的实现。

问题

我可能缺少一些东西,因为我在上面描述的实现无法正常运行。我怎么知道的,上面的Qt Docs和SO文章都提到QThread :: quit()或QThread :: exit()依赖于QEventLoop,并且如果QThread :: exec()没有运行(通过调用通过QThread :: start()通过QThread :: run(),那么quit()或exit()函数将永远不会运行,这是我的问题。

我的实现哲学类似于Java的Thread&Lambda语法,例如

1
new Thread(() -> { // some code to run in a different thread}).start();

我使用以下实现

可以使用lambda的各种线程对象容器

1
2
3
4
5
6
7
QWorkerThread: public QObject

    // This is the thread that runs object below
----QWaitThread : public QThread

    // This is the object which lives inside the above thread
----ThreadWorker : public QObject, public QInterruptable

一个简单的示例用法是(在QWorkerThread内部完成线程和子对象清除):

1
2
3
4
5
QWorkerThread *workerThread = new QWorkerThread;
workerThread->setRunnable([](){
    // insert CPU intensive or long running task here
});
workerThread->start();

问题详细信息/示例

1
2
// somewhere in main UI thread
workerThread->stop(); // or workerThread->kill()

调用QThread::quit()或QThread::quit(),然后QThread::terminate()后跟QThread::wait()不会终止线程。 lambda(在setRunnable()内部)中定义的长时间运行的过程将一直运行到完成为止。

我知道这篇文章比常规文章更长,但是我希望每个人都能获得我要实现的目标的完整"图景",因为我不确定问题的根源。

任何帮助将不胜感激!

代码实施

如果我错过了一些重要的事情,我将发布所有代码以获得完整的实现想法。

QWaitThread.h是QThread的实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#ifndef QWAITTHREAD_H
#define QWAITTHREAD_H

#include <QObject>
#include <QThread>
#include <QWaitCondition>
#include <QMutex>

class QWaitThread : public QThread
{
    Q_OBJECT
public:
    explicit QWaitThread(QObject *parent = nullptr);
    ~QWaitThread();
    virtual void pause();
    virtual void resume();    

signals:
    void paused();
    void resumed();

public slots:
    void pausing();
    void resuming();

private:
    QWaitCondition *waitCondition;
    QMutex mutex;
};

#endif // QWAITTHREAD_H

QWaitThread.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include"qwaitthread.h"

QWaitThread::QWaitThread(QObject *parent) : QThread(parent)
{
    waitCondition = new QWaitCondition;
}

QWaitThread::~QWaitThread()
{
    if(waitCondition != nullptr) {
        delete waitCondition;
    }
}

void QWaitThread::pause()
{
    emit paused();
    waitCondition->wait(&mutex);
}

void QWaitThread::resume()
{
    waitCondition->wakeAll();
    emit resumed();
}

void QWaitThread::pausing()
{
    pause();
}

void QWaitThread::resuming()
{
    resume();
}

QInterruptable.h接口定义了一些预期的功能

1
2
3
4
5
6
7
8
9
10
11
12
#ifndef QINTERRUPTABLE_H
#define QINTERRUPTABLE_H

class QInterruptable {
public:
    virtual void pause() = 0;
    virtual void resume() = 0;
    virtual void interrupt() = 0;
    virtual ~QInterruptable() = default;
};

#endif // QINTERRUPTABLE_H

ThreadWorker.h是QWaitThread内部(并运行)的对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#ifndef THREADWORKER_H
#define THREADWORKER_H

#include <QObject>
#include <functional>
#include <QWaitCondition>
#include <QMutex>

#include"QInterruptable.h"

class ThreadWorker : public QObject, public QInterruptable
{
    Q_OBJECT

private:
    QMutex mutex;
    QWaitCondition *waitCondition;
    std::function<void ()> runnable;
    bool shouldPause = false;

public:
    explicit ThreadWorker(QObject *parent = nullptr);
    ThreadWorker(std::function<void ()> func);
    ~ThreadWorker();

    void setRunnable(const std::function<void ()> &value);

signals:
    /**
     * Emitted when the QWorkerThread object has started work
     * @brief started
     */

    void started();

    /**
     * @brief progress reports on progress in method, user defined.
     * @param value reported using int
     */

    void progress(int value);

    /**
     * Emitted when the QWorkerThread object has finished its work, same signal is used from &QThread::finished
     * @brief started
     */

    void finished();

    /**
     * Emitted when the QWorkerThread has encountered an error, user defined.
     * @brief started
     */

    void error();

public slots:
    virtual void run();
    virtual void cleanup();


    // QInterruptable interface
public:
    void pause()
    {
        shouldPause = true;
    }
    void resume()
    {
        shouldPause = false;
    }
    QMutex& getMutex();
    QWaitCondition *getWaitCondition() const;
    void setWaitCondition(QWaitCondition *value);
    bool getShouldPause() const;

    // QInterruptable interface
public:
    void interrupt()
    {

    }
};

#endif // THREADWORKER_H

ThreadWorker.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include"threadworker.h"

void ThreadWorker::setRunnable(const std::function<void ()> &value)
{
    runnable = value;
}

QMutex& ThreadWorker::getMutex()
{
    return mutex;
}

QWaitCondition *ThreadWorker::getWaitCondition() const
{
    return waitCondition;
}

void ThreadWorker::setWaitCondition(QWaitCondition *value)
{
    waitCondition = value;
}

bool ThreadWorker::getShouldPause() const
{
    return shouldPause;
}

ThreadWorker::ThreadWorker(QObject *parent) : QObject(parent)
{
    waitCondition = new QWaitCondition;
}

ThreadWorker::ThreadWorker(std::function<void ()> func): runnable(func) {
    waitCondition = new QWaitCondition;
}


ThreadWorker::~ThreadWorker()
{    
    if(waitCondition != nullptr){
        delete waitCondition;
    }
}

void ThreadWorker::run()
{
    emit started();
    runnable();
    emit finished();
}

void ThreadWorker::cleanup()
{

}

QWorkerThread.h是感兴趣的主要类,在其中接受可运行的lambda,并且在其中发生主要的"线程"处理,移至线程,启动线程,处理事件等

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#ifndef QWORKERTHREAD_H
#define QWORKERTHREAD_H

#include <QObject>
#include <functional>
#include <QThread>
#include <QEventLoop>

#include"qwaitthread.h"
#include"threadworker.h"

class QWorkerThread: public QObject
{
    Q_OBJECT

public:

    enum State {
        Running,
        Paused,
        NotRunning,
        Finished,
        Waiting,
        Exiting
    };

    QWorkerThread();
    explicit QWorkerThread(std::function<void ()> func);
    ~QWorkerThread();
    static QString parseState(QWorkerThread::State state);
    virtual void setRunnable(std::function <void()> runnable);
    virtual void start(QThread::Priority priority = QThread::Priority::InheritPriority);
    virtual void stop();
    virtual void wait(unsigned long time = ULONG_MAX);
    virtual void kill();
    virtual void setWorkerObject(ThreadWorker *value);

    virtual void pause();
    virtual void resume();
    virtual QWaitThread *getWorkerThread() const;

    State getState() const;


signals:
    /**
     * Emitted when the QWorkerThread object has started work
     * @brief started
     */

    void started();

    /**
     * @brief progress reports on progress in method, user defined.
     * @param value reported using int
     */

    void progress(int value);

    /**
     * Emitted when the QWorkerThread object has finished its work, same signal is used from &QThread::finished
     * @brief started
     */

    void finished();

    /**
     * Emitted when the QWorkerThread has encountered an error, user defined.
     * @brief started
     */

    void error();

private:
    /**
     * @brief workerObject - Contains the object and 'method' that will be moved to `workerThread`
     */

    ThreadWorker *workerObject = nullptr;

    /**
     * @brief workerThread - Worker Thread is seperate thread that runs the method
     */

    QWaitThread *workerThread = nullptr;

    State state = State::NotRunning;

};

#endif // QWORKERTHREAD_H

QWorkerThread.cpp实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
#include"qworkerthread.h"

QWorkerThread::QWorkerThread()
{
    state = State::NotRunning;
    workerThread = new QWaitThread;
    workerObject = new ThreadWorker;
    workerThread->setObjectName("WorkerThread");
}

QWorkerThread::QWorkerThread(std::function<void ()> func)
{
    state = State::NotRunning;
    workerThread = new QWaitThread;
    workerObject = new ThreadWorker(func);
    workerThread->setObjectName("WorkerThread");
}

QWorkerThread::~QWorkerThread()
{
    //  Check if worker thread is running
    if(workerThread->isRunning()) {

        // Exit thread with -1
        workerThread->exit(-1);
    }

    if(!workerThread->isFinished()) {
        workerThread->wait(500);

        if(workerThread->isRunning()) {
            workerThread->terminate();
        }
    }

    // cleanup
    delete workerObject;
    delete workerThread;
}

void QWorkerThread::setRunnable(std::function<void ()> runnable)
{
    workerObject->setRunnable(runnable);
}

void QWorkerThread::start(QThread::Priority priority)
{

    state = State::Running;
    // Connect workerThread start signal to ThreadWorker object's run slot
    connect(workerThread, &QThread::started, workerObject, &ThreadWorker::started);
    connect(workerThread, &QThread::started, workerObject, &ThreadWorker::run);

    // Connect threadWorker progress report to this progress report
    connect(workerObject, &ThreadWorker::progress, this, &QWorkerThread::progress);

    // Cleanup
    connect(workerObject, &ThreadWorker::finished, this, [this](){
        state = State::Finished;
        emit finished();
    });
    connect(workerThread, &QWaitThread::finished, this, [this] {
        workerObject->deleteLater();
    });

    // move workerObject to thread
    workerObject->moveToThread(workerThread);

    // emit signal that we are starting
    emit started();

    // Start WorkerThread which invokes object to start process method
    workerThread->start(priority);
}

void QWorkerThread::stop()
{
    state = State::Exiting;
    // Exit thread safely with success
    workerThread->quit();

    emit finished();
}

void QWorkerThread::wait(unsigned long time)
{
    state = State::Waiting;
    workerThread->wait(time);
}

void QWorkerThread::kill()
{
    // try stopping
    stop();

    // check if still running
    if(workerThread->isRunning()){
        // forcefully kill
        workerThread->terminate();
        workerThread->wait();
    }

    emit finished();
}

void QWorkerThread::setWorkerObject(ThreadWorker *value)
{
    workerObject = value;
}

QWaitThread *QWorkerThread::getWorkerThread() const
{
    return workerThread;
}

QWorkerThread::State QWorkerThread::getState() const
{
    return state;
}

QString QWorkerThread::parseState(QWorkerThread::State state) {
    switch (state) {
        case Running:
            return"Running";
        case Paused:
            return"Paused";
        case NotRunning:
            return"NotRunning";
        case Finished:
            return"Finished";
        case Waiting:
            return"Waiting";
        case Exiting:
            return"Exiting";
    }

    return QString("Unknown State [%1]").arg(QString::number(state)) ;
}

void QWorkerThread::pause()
{
    workerObject->pause();
    state = State::Paused;
}

void QWorkerThread::resume()
{
    workerObject->resume();
    state = State::Running;
}

更新一些额外的信息

关于~QWorkerThread(),我注意到在调用delete QThread或QThread::deleteLater()时,QWaitThread()(或QThread)将引发致命错误:线程在运行时被销毁。这是在调用quit() / terminate()之后。

来自QThread.cpp的以下行

1
2
if (d->running && !d->finished && !d->data->isAdopted)
    qFatal("QThread: Destroyed while thread is still running");

哪里

1
2
3
d->running == true
d->finished == false
d->data->isAdopted ?


我已经测试了您的代码,这就是我意识到的。
如您所述,terminate()不会完全停止线程。
Qt doc说:

Terminates the execution of the thread. The thread may or may not be terminated immediately, depending on the operating system's scheduling policies. Use QThread::wait() after terminate(), to be sure.

不幸的是,wait()即使在terminate()之后也会冻结。您的代码可能有问题,但是我创建了一个最大限度简化的示例来验证这一点,但仍然存在相同的问题。

首先,这是您建议修改的部分代码:

1
2
3
4
5
6
7
QWorkerThread::~QWorkerThread()
{
    ...
    // cleanup
    delete workerObject; // Unsafe, but the only way to call the destructor, if necessary
    delete workerThread; // qFatal
}

这是Qt doc关于析构函数不安全性的说法:

从拥有该对象的线程之外的线程上调用QObject上的delete(或以其他方式访问该对象)是不安全的,除非您保证该对象当时不处理事件。使用QObject::deleteLater()代替,将发布一个DeferredDelete事件,该事件最终将拾取该对象线程的事件循环。默认情况下,拥有QObject的线程是创建QObject的线程,但不是在调用QObject::moveToThread()之后。

注意。将delete workerThread更改为workerThread->deleteLater()对我来说不需要qFatal。

好的,我们实际上有什么问题:

  • 由于qFatal,不能直接在terminate()之后调用QThread子类的Desctructor
  • wait()冻结,尽管有文档也不能在terminate()之后使用
  • (似乎只有在将无限操作移入事件循环时该问题才是实际的)

    确保问题不在代码的其他位置

    最小可复制示例

    工人

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    #pragma once

    #include <QObject>

    class Worker : public QObject
    {
        Q_OBJECT

    public:
        ~Worker();

    public slots:
        void process();
    };

    工作人员

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    #include"Worker.h"
    #include <QThread>
    #include <QDebug>
    #include <QDateTime>

    Worker::~Worker()
    {
        qDebug() <<"~Worker()";
    }

    void Worker::process()
    {
        qDebug("Hello World!");

        while(true)
        {
            qDebug() << QDateTime::currentDateTime();
            QThread::msleep(100);
        }
    }

    主程序

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    #pragma once

    #include <QtWidgets/QMainWindow>

    class QThread;
    class Worker;

    class MainWin : public QMainWindow
    {
        Q_OBJECT

    public:
        MainWin(QWidget *parent = nullptr);
        ~MainWin();

    private:
        QThread*    thread = nullptr;
        Worker*     worker = nullptr;
    };

    MainWin.cpp

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    #include"MainWin.h"
    #include"Worker.h"
    #include <QThread>
    #include <QDebug>
    #include <QDateTime>

    MainWin::MainWin(QWidget *parent)
      : QMainWindow(parent)
    {
        thread = new QThread;
        worker = new Worker;

        worker->moveToThread(thread);

        // Start only one infinite operation
        connect(thread, &QThread::started, worker, &Worker::process);

        thread->start();
    }

    MainWin::~MainWin()
    {
        if (thread->isRunning())
        {
            thread->exit(-1);
            thread->wait(500);
        }

        if (thread->isRunning())
        {
            thread->terminate();
        }

        //cleanup
        delete worker;
        delete thread; // qFatal("QThread: Destroyed while thread is still running")
    }

    我发现的唯一工作代码

    1
    2
    3
    4
    5
    6
    7
    MainWin::~MainWin()
    {
        ...
        //cleanup
        delete worker; // Worker destructor will be called, but be note this is unsafe
        thread->deleteLater(); // Allows to avoid qFatal but make thread terminated
    }

    结论与建议

    除了可以完全避免使用terminate()之外,我所能提供的一切就是使用terminate()而不使用wait(),然后使用workerThread->deleteLater()。

    如果您要终止的耗时操作是您自己的代码,请考虑将一些终止标志嵌入到代码中。

    最好避免使用原始指针,并在可能的情况下将其替换为智能指针。

    我还能提供什么作为在线程中运行lambda的通用方法

    简化示例如何使用lamda,信号插槽,线程,已完成的信号QtConcurrent::run()和QFuture<>。这样,您既可以在一个持久性附加线程中实现代码,也可以在自动线程池中实现代码。但是不支持终止。

    LambdaThread.h

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    #pragma once

    #include <QObject>
    #include <functional>
    #include <QFuture>

    class QThreadPool;

    class LambdaThread : public QObject
    {
        Q_OBJECT

    public:
        // maxThreadCount = -1 to use idealThreadCount by default
        LambdaThread(QObject *parent, int maxThreadCount = -1);

    signals:
        void started();
        void finished();

    public slots:
        // Invoke this directly or by a signal
        QFuture<void> setRunnable(std::function<void()> func);

    private:
        /*
        For the case you need persistent thread sometimes.
        In the case you never need persistent thread,
        just remove m_threadPool from this class at all
        */

        QThreadPool* m_threadPool = nullptr;
    };

    LambdaThread.cpp

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    #include"LambdaThread.h"
    #include <QtConcurrent/QtConcurrent>
    #include <QThreadPool>

    LambdaThread::LambdaThread(QObject *parent, int maxThreadCount /*= -1*/)
        : QObject(parent)
    {
        m_threadPool = new QThreadPool(this);

        if(maxThreadCount > 0)
        {
            m_threadPool->setMaxThreadCount(maxThreadCount);

            if (maxThreadCount == 1)
            {
                // Avoid thread affinity changing
                m_threadPool->setExpiryTimeout(-1);
            }
        }
    }

    QFuture<void> LambdaThread::setRunnable(std::function<void()> func)
    {
        return QtConcurrent::run(m_threadPool,
            [this, func]()
        {
            // Be note that you actually need event loop in a receiver thread only
            emit started();

            func();

            emit finished();
        });
    }

    只是GUI类的示例,您可以在其中启动可运行对象并接收信号。

    主程序

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    #pragma once

    #include <QtWidgets/QMainWindow>
    #include <functional>

    class LambdaThread;

    class MainWin : public QMainWindow
    {
        Q_OBJECT

    public:
        MainWin(QWidget *parent = nullptr);

    signals:
        // For the case you want to use signals
        void newRunnable(std::function<void()> func);

    private:
        LambdaThread* m_lambdaThread = nullptr;
    };

    MainWin.cpp

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    #include"MainWin.h"
    #include"LambdaThread.h"
    #include <QFuture>
    #include <QDebug>

    MainWin::MainWin(QWidget *parent)
        : QMainWindow(parent)
    {
        m_lambdaThread = new LambdaThread(this);

        connect(this, &MainWin::newRunnable,
            m_lambdaThread, &LambdaThread::setRunnable);

        /*
        Do not forget the third (`this`) context variable
        while using modern signal-slot connection syntax with lambdas
        */

        connect(m_lambdaThread, &LambdaThread::started,
            this, []()
        {
            qDebug() <<"Runnable stated";
        });

        connect(m_lambdaThread, &LambdaThread::finished,
            this, []()
        {
            qDebug() <<"Runnable finished";
        });

        // Set your lambda directly
        QFuture<void> future = m_lambdaThread->setRunnable([]()
        {
            qDebug() <<"hello from threaded runnable";
        });

        // You can also use future (not necessary of course)
        //future.waitForFinished();

        // Or you can emit your lambda via the signal:
        emit newRunnable([]()
        {
            qDebug() <<"hello from threaded runnable which comes from signal";
        });
    }