QThread :: finished () is never released?

I don't have a forever loop like this question , but it still does not emit a ready () signal,

In the class constructor:

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() call being called, every time before I start the thread with thread.start() , I have to call thread.terminate() manually, did I not understand the use of QThread?

+1
source share
1 answer

QThread will emit a finished signal when the QThread::run method is finished. Perhaps you have the wrong implementation of this.

The default implementation of the run method looks like this. It just calls another exec method.

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

Implementing the exec method is a bit more complicated. Now I have simplified it.

 int QThread::exec() { // ..... if (d->exited) { return d->returnCode; } // ...... QEventLoop eventLoop; int returnCode = eventLoop.exec(); return returnCode; } 

Judging by the code, it can be completed in two cases. In the first case, if he has already left. Secondly, it enters the event loop and waits until exit() called.

As we can see now, your infinity flow cycle is here. So you need QThread::quit() equal to QThread::exit(0) .

PS Do not use terminate . This is dangerous.

+1
source

Source: https://habr.com/ru/post/1446556/


All Articles