Skip to main content
 首页 » 编程设计

python之清理没有 .join() 且不阻塞主线程的线程

2024年11月24日10cloudgamer

我处于这样一种情况,我有两个端点可以请求一个值,并且一个可能比另一个更快。对端点的调用正在阻塞。我想等待一个完成并获取该结果,而无需等待另一个完成。

我的解决方案是在单独的线程中发出请求,并让这些线程在完成时将标志设置为 true。在主线程中,我不断检查标志(我知道这是一个繁忙的等待,但这不是我现在最关心的问题),当一个完成时,它获取该值并将其作为结果返回。

我遇到的问题是我从不清理其他线程。如果不使用 .join(),我找不到任何方法来做到这一点,这只会阻止并破坏整个事情的目的。那么,如何在不从主线程加入的情况下清理阻塞的其他速度较慢的线程?

请您参考如下方法:

你想要的是让你的线程成为daemon,所以当你得到结果并完成你的main时,其他正在运行的线程将被强制完成。您可以通过将 daemon 关键字更改为 True 来实现:

tr = threading.Thread(daemon=True) 

来自threading文档:

The significance of this flag is that the entire Python program exits when only daemon threads are left.

虽然:

Daemon threads are abruptly stopped at shutdown. Their resources (such as open files, database transactions, etc.) may not be released properly. If you want your threads to stop gracefully, make them non-daemonic and use a suitable signalling mechanism such as an Event.

我对 Event 没有任何特殊经验,因此无法详细说明。请随时单击链接并继续阅读。