Qt, How to pause QThread immediately

2019-02-19 14:18发布

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.

标签: qt qthread
1条回答
太酷不给撩
2楼-- · 2019-02-19 14:30

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".

查看更多
登录 后发表回答