QThread :: quit () immediately terminates the thread, or does it wait until it returns to the event loop?

There are many multithreaded Qt tutorials that indicate that QThreadyou can safely stop using the following two lines.

qthread.quit(); // Cause the thread to cease.
qthread.wait(); // Wait until the thread actually stops to synchronize.

I have a lot of code, and in most cases when the thread stops, I always set my own cancel flag and often check it at runtime (like the norm). Until now, I thought that calling quit could cause the thread to simply stop executing any wait signals (for example, signals that are queued will no longer call their slots), but still wait for the current executable slot to finish .

But I wonder if I was right or if it quit()actually stops the thread from executing where it is, for example, if something is unfinished, like the file descriptor was not closed, this should definitely be, although in most cases my work objects will clear these resources , I would be better if I knew exactly how to stop work.

I ask this because the documentation QThread::quit()says that this is equivalent to calling QThread :: exit (0). "I believe this means that the thread will immediately stop where it is. But what happens to the higher stack structure?

+7
source share
2 answers

QThread::quit , - . .

, QThread::quit . , .

- , , , . -, , , . (, ), . , , .

QThread::terminate(), , , , , . , . :

: . . . , .. , .

, , :

myThread->m_abort = true; //Tell the thread to abort
if(!myThread->wait(5000)) //Wait until it actually has terminated (max. 5 sec)
{
  myThread->terminate(); //Thread didn't exit in time, probably deadlocked, terminate it!
  myThread->wait(); //We have to wait again here!
}
+7

, QThread::requestInterruption() Qt, QThread::requestInterruption().

struct X {
  QThread m_Thread; 
  void Quit ()
  {
    m_Thread.quit();
    m_Thread.requestInterruption();
  }
};

, X::m_Thread

while(<condition>) {
  if(QThread::currentThread()->isInterruptionRequested())
    return;
  ...
}

:

void QThread :: requestInterruption()

. , , , , . - .

0

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


All Articles