1

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?

4

1 回答 1

2

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.

于 2012-10-18T04:55:12.850 回答