0

我有两个类——一个在主线程中运行并执行 GUI 操作,另一个执行一些计算并发出网络请求。

// A member of the class that runs in the main thread
QThread thread;

这是在主线程中运行的类的初始化方法的片段:

// Create the class that runs in the other thread and move it there
CServerThread * server = new CServerThread;
server->moveToThread(&thread);

// When the thread terminates, we want the object destroyed
connect(&thread, SIGNAL(finished()), server, SLOT(deleteLater()));
thread.start();

在主线程中运行的类的析构函数中:

if(thread.isRunning())
{
    thread.quit();
    thread.wait();
}

我期望发生的是线程终止并销毁CServerThread类的实例。但是,CServerThread该类的析构函数没有被调用。

4

1 回答 1

5

QThread::quit()停止该线程的事件循环。

告诉线程的事件循环以返回码 0(成功)退出。

QObject::deleteLater()需要“拥有”线程的事件循环处于活动状态:

计划删除此对象。
当控制返回事件循环时,该对象将被删除。

所以你的对象的析构函数不会运行,finished信号被触发太晚了。

考虑下面的人为示例:

#include <QThread>
#include <iostream>

class T: public QObject
{
    Q_OBJECT

    public:
        QThread thr;
        T() {
            connect(&thr, SIGNAL(finished()), this, SLOT(finished()));
        };
        void start() {
            thr.start();
            std::cout << "Started" << std::endl;
        }
        void stop() {
            thr.quit();
            std::cout << "Has quit" << std::endl;
        }
        void end() {
            thr.wait();
            std::cout << "Done waiting" << std::endl;
        }
    public slots:
        void finished() {
            std::cout << "Finished" << std::endl;
        }
};

如果你打电话:

T t;
t.start();
t.stop();
t.end();

输出将是:

Started
Has quit
Done waiting
Finished

finished完成后触发wait。为时已晚,您的deleteLater连接无法生效,该线程的事件循环已经死了。

于 2011-10-23T07:31:20.100 回答