I have an QThread
which listen server. I want to pause work of QThread
immediately. Not waiting at all, but almost like terminating, it must be immediate.
A code running in any given thread cannot be stopped at an arbitrary point without corrupting the state of the shared data structures in your code and/or the C/C++ runtime or any other libraries that are used.
The code can only stop at well-defined points.
If your thread runs an event loop (i.e. usually if you don't derive from QThread
or don't override its run
), then QThread::quit()
will stop the thread once it returns control to the event loop, where it's safe to do so.
If your thread reimplements run and executes a loop there, it should return when interruption is requested:
void MyThread::run() {
while (! isInterruptionRequested()) {
...
}
}
Such a thread is stoppable by QThread::requestInterruption()
.
For reference, here are various methods of QThread
that are sometimes confused:
wait()
blocks the calling thread until the called thread finishes. Of course, calling it from within the thread itself is instant deadlock: a thread can't finish if it waits for something that's never going to happen.quit()
quits the thread's event loop at the earliest opportunity, and causesQThread::run()
to return. It does nothing if you're reimplementedrun()
and don't spin an event loop.requestTermination()
sets a flag that a custom loop inYourThread::run()
can check viaisTerminationRequested()
.terminate()
stops the thread now. This generally corrupts the state of your application, so you mustabort()
sometime soon or face the consequences. This method is best forgotten about. It essentially means "crash this process soon and corrupt some disk data if you get a chance".
© 2022 - 2024 — McMap. All rights reserved.