Qt,如何立即暂停 QThread [英] Qt, How to pause QThread immediately

查看:240
本文介绍了Qt,如何立即暂停 QThread的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 QThread 监听服务器.我想立即暂停 QThread 的工作.根本不等待,但几乎就像终止一样,必须立即进行.

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.

推荐答案

在任何给定线程中运行的代码不能在任意点停止而不破坏代码和/或 C/C++ 中共享数据结构的状态运行时或任何其他使用的库.

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.

如果您的线程运行事件循环(即通常如果您不是从 QThread 派生或不覆盖其 run),则 QThread::quit() 将在线程将控制权返回给事件循环后停止线程,在那里这样做是安全的.

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.

如果你的线程重新实现 run 并在那里执行一个循环,它应该在请求中断时返回:

If your thread reimplements run and executes a loop there, it should return when interruption is requested:

void MyThread::run() {
  while (! isInterruptionRequested()) {
    ...
  }
}

这样的线程可以被 QThread::requestInterruption() 停止.

Such a thread is stoppable by QThread::requestInterruption().

参考,这里是QThread的各种方法,有时会混淆:

For reference, here are various methods of QThread that are sometimes confused:

  • wait() 阻塞调用线程,直到被调用线程完成.当然,从线程内部调用它本身就是即时死锁:如果线程等待永远不会发生的事情,它就无法完成.

  • 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() 尽早退出线程的事件循环,并导致 QThread::run() 返回.如果您重新实现了 run() 并且不旋转事件循环,则它什么都不做.

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() 设置一个标志,YourThread::run() 中的自定义循环可以通过 isTerminationRequested() 检查该标志.

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

terminate()现在停止线程.这通常会破坏应用程序的状态,因此您必须尽快abort() 否则将面临后果.这种方法最好忘记.它本质上的意思是如果有机会,尽快使此进程崩溃并损坏一些磁盘数据".

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

这篇关于Qt,如何立即暂停 QThread的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆