QThread::finished() is never emitted?

梦想的初衷 提交于 2019-12-11 06:35:49

问题


I don't have a forever loop like this question, but it still doesn't emit the finished() signal,

In the constructor of a class:

connect (&thread, SIGNAL(started()), SLOT(threadFunc()));
connect (&thread, SIGNAL(finished()), SLOT(finished()));

In the finished() function,

void XX::finished()
{
  qDebug() << "Completed";
}

void XX::threadFunc()
{
  qDebug() << "Thread finished"; // only single line, finishes immediately
}

But I never see the finished() get called, everytime before I start the thread with thread.start(), I must call thread.terminate() manually, did I misunderstood the usage of QThread?


回答1:


QThread will emit finished signal when QThread::run method is finished. Perhaps, you have incorrect implementation of this.

Default implementation of run method looks like this. It just calls another exec method.

void QThread::run()
{
    (void) exec();
}

Implementation of exec method is a bit more complex. Now I simplified it.

int QThread::exec()
{
    // .....

    if (d->exited) {
        return d->returnCode;   
    }

    // ......

    QEventLoop eventLoop;
    int returnCode = eventLoop.exec();
    return returnCode;
}

Judging by code, it can finish in two cases. In first case if it is already exited. In second it enters the event loop and waits until exit() is called.

How we can see now, your infinity thread loop is here. So you need QThread::quit() which is equal QThread::exit(0).

P.S. Don't use terminate. It is dangerous.



来源:https://stackoverflow.com/questions/12946209/qthreadfinished-is-never-emitted

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!