python 中的线程是否需要连接以避免泄漏?
Do threads in python need to be joined to avoid leakage?
我明白加入一个线程的目的,我问的是资源使用。我这里的具体用例是我有一个长 运行 的进程,需要生成许多线程,并在运行期间检查它们是否已终止,然后清理它们。主线程等待 inotify 事件并根据这些生成线程,因此它不能阻塞 join()
调用,因为它需要阻塞 inotify 调用。
我知道,例如,对于 pthreads,不加入已终止的线程会导致资源泄漏:
PTHREAD_JOIN(3): Failure to join with a thread that is joinable (i.e., one that is not detached), produces a "zombie thread". Avoid doing this, since each zombie thread consumes some system resources, and when enough zombie threads have accumulated, it will no longer be possible to create new threads (or processes).
Python's documentation says no such thing, but it does also does not specify that the join() can be disregarded without issue if many threads are expected to end on their own without being joined在正常操作期间。
我想知道,我能否简单地获取我的主题列表并执行以下操作:
threads = [thread for thread in threads if thread.is_alive()]
每次检查,还是会漏水?或者我必须执行以下操作吗?
alive_threads = list()
for thread in threads:
if thread.is_alive():
alive_threads.append(thread)
else:
thread.join()
threads = alive_threads
TLDR:否。Thread
自行清理底层资源。
Thread.join
只是等待线程结束,它不执行清理。基本上,每个 Thread
都有一个锁,在线程完成并随后清理时释放。 Thread.join
只是等待锁被释放。
Thread.join
进行了一些小的清理工作,即删除锁并设置一个标志以将线程标记为死线程。这是一种避免不必要地等待锁的优化。然而,这些是内部的,并且也由依赖锁和标志的所有其他 public 方法执行。最后,此清理在功能上等同于 Thread
由于垃圾收集而自动清理。
我明白加入一个线程的目的,我问的是资源使用。我这里的具体用例是我有一个长 运行 的进程,需要生成许多线程,并在运行期间检查它们是否已终止,然后清理它们。主线程等待 inotify 事件并根据这些生成线程,因此它不能阻塞 join()
调用,因为它需要阻塞 inotify 调用。
我知道,例如,对于 pthreads,不加入已终止的线程会导致资源泄漏:
PTHREAD_JOIN(3): Failure to join with a thread that is joinable (i.e., one that is not detached), produces a "zombie thread". Avoid doing this, since each zombie thread consumes some system resources, and when enough zombie threads have accumulated, it will no longer be possible to create new threads (or processes).
Python's documentation says no such thing, but it does also does not specify that the join() can be disregarded without issue if many threads are expected to end on their own without being joined在正常操作期间。
我想知道,我能否简单地获取我的主题列表并执行以下操作:
threads = [thread for thread in threads if thread.is_alive()]
每次检查,还是会漏水?或者我必须执行以下操作吗?
alive_threads = list()
for thread in threads:
if thread.is_alive():
alive_threads.append(thread)
else:
thread.join()
threads = alive_threads
TLDR:否。Thread
自行清理底层资源。
Thread.join
只是等待线程结束,它不执行清理。基本上,每个 Thread
都有一个锁,在线程完成并随后清理时释放。 Thread.join
只是等待锁被释放。
Thread.join
进行了一些小的清理工作,即删除锁并设置一个标志以将线程标记为死线程。这是一种避免不必要地等待锁的优化。然而,这些是内部的,并且也由依赖锁和标志的所有其他 public 方法执行。最后,此清理在功能上等同于 Thread
由于垃圾收集而自动清理。