Qt, How to pause QThread immediately
Asked Answered
D

1

6

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.

Disconcert answered 30/8, 2016 at 15:57 Comment(4)
Can you provide some code. It's not clear now what you mean. As you see, msleep method pause work of thread immediately. Is it what you want?Scribble
"it must cut like knife" O_oKramatorsk
run function of QThread emit a signal. I want to terminate stuff alrealdy works emitted by signal.Disconcert
Are you using Qt networking classes, or some other (blocking) listen call? Anyway, this question needs the relevant code!Fugazy
S
22

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 causes QThread::run() to return. It does nothing if you're reimplemented run() and don't spin an event loop.

  • requestTermination() sets a flag that a custom loop in YourThread::run() can check via isTerminationRequested().

  • terminate() stops the thread now. This generally corrupts the state of your application, so you must abort() 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".

Salep answered 30/8, 2016 at 20:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.