我没有永远循环like this question ,但它仍然没有发出 finish() 信号,
在类的构造函数中:
connect (&thread, SIGNAL(started()), SLOT(threadFunc()));
connect (&thread, SIGNAL(finished()), SLOT(finished()));
在finished()函数中,
void XX::finished()
{
qDebug() << "Completed";
}
void XX::threadFunc()
{
qDebug() << "Thread finished"; // only single line, finishes immediately
}
但我从来没有看到 finished()
被调用,每次在使用 thread.start()
启动线程之前,我都必须调用 thread.terminate ()
手动,我是否误解了QThread的用法?
最佳答案
当QThread::run
方法完成时,
QThread
将发出finished
信号。也许,你对此的实现不正确。
run
方法的默认实现如下所示。它只是调用另一个 exec
方法。
void QThread::run()
{
(void) exec();
}
exec
方法的实现有点复杂。现在我简化了它。
int QThread::exec()
{
// .....
if (d->exited) {
return d->returnCode;
}
// ......
QEventLoop eventLoop;
int returnCode = eventLoop.exec();
return returnCode;
}
从代码来看,可以分两种情况完成。在第一种情况下,如果它已经退出。第二步,它进入事件循环并等待 exit()
被调用。
我们现在可以看到,你的无限线程循环就在这里。因此,您需要 QThread::quit()
,它等于 QThread::exit(0)
。
P.S. 不要使用终止
。很危险。
关于multithreading - QThread::finished() 从未被发出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12946209/