Nat*_*man 0 qt destructor qthread
我有两个类 - 一个在主线程中运行并执行GUI操作,另一个执行一些计算并发出网络请求.
// A member of the class that runs in the main thread
QThread thread;
Run Code Online (Sandbox Code Playgroud)
这是在主线程中运行的类的初始化方法的片段:
// 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();
Run Code Online (Sandbox Code Playgroud)
在主线程中运行的类的析构函数中:
if(thread.isRunning())
{
thread.quit();
thread.wait();
}
Run Code Online (Sandbox Code Playgroud)
我期望发生的是线程终止并销毁CServerThread类的实例.但是,CServerThread不会调用该类的析构函数.
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;
}
};
Run Code Online (Sandbox Code Playgroud)
如果你打电话:
T t;
t.start();
t.stop();
t.end();
Run Code Online (Sandbox Code Playgroud)
输出将是:
Started
Has quit
Done waiting
Finished
Run Code Online (Sandbox Code Playgroud)
finishedwait完成后触发.为了使你的deleteLater连接生效太晚,该线程的事件循环已经死了.
| 归档时间: |
|
| 查看次数: |
1984 次 |
| 最近记录: |