如何终止一个QThread?
QThread::terminate()
文档指出,不鼓励通过调用此函数来终止线程。
在我的程序中,我需要在线程完成执行之前终止它。该线程正在执行一些繁重的计算,我希望用户能够控制停止计算。
我怎样才能做到这一点而不是调用QThread::terminate()
?
QThread::terminate()
documentation states that it is discouraged to terminate a thread by calling this function.
In my program, I need to terminate a thread before it finishes execution. The thread is performing some heavy computation and I want the user to have control to stop calculation.
How can I do that instead of calling QThread::terminate()
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
从线程外部设置一个标志,该标志由线程内的计算检查,如果设置了标志,则停止计算。
Set a flag from outside the thread that is checked by the computation within the thread and stop the calculation if the flag is set.
使用标志是一种明显且最常见的方法,但如果您在 linux/unix 平台上工作,我建议您改用管道。我在使用标志时遇到了同样的问题(这使得代码线程不安全,并且很难跟踪由此类标志引起的错误),然后我更改了实现以使用管道,这是完成所需任务的有效方法。
如果您愿意,对于 Linux 平台,我可以向您展示如何使用管道来终止 QThread。
您可能还拥有相当于管道的Windows,但我对此不太了解,因为我没有在Windows 平台上进行过太多编程。
希望这有帮助
Using flags is an obvious and the most common way to do the trick, but if you are working on a linux/unix platform I would advise you to use pipes instead. I had the same issue where I used a flag (this makes the code threadunsafe, and bugs arising out of such a flag are hard to trace), then I changed the implementation to use pipes which were an efficient way to do the needful.
If you want, for a linux platform I can show you how to use pipes to terminate a QThread.
You may also have windows equivalent of pipes, which I don't know much about as I haven't done much of programming on Windows platform.
Hope this helps
最好是使用标志+互斥体,这将使解决方案线程安全。
Best is to use flag + mutex which will make the solution thread safe.