如何终止一个QThread?

发布于 2024-08-02 15:01:22 字数 173 浏览 6 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

你是暖光i 2024-08-09 15:01:22

从线程外部设置一个标志,该标志由线程内的计算检查,如果设置了标志,则停止计算。

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.

烟若柳尘 2024-08-09 15:01:22

使用标志是一种明显且最常见的方法,但如果您在 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

风向决定发型 2024-08-09 15:01:22

最好是使用标志+互斥体,这将使解决方案线程安全。

Best is to use flag + mutex which will make the solution thread safe.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文