使用 __stop 停止的线程不会从 threading.enumerate() 中删除

threads stopped using __stop are not removed from threading.enumerate()

基本上,我有一些线程可能会在 I/O 上阻塞,但在某些情况下必须停止。整个软件架构已经是这样设计的,因此切换到多处理可能会很痛苦。因此,我在网上搜索,发现使用 thread_ref._Thread__stop() 似乎是唯一可以保证停止阻塞线程的方法。

现在的问题是,尽管该线程已停止,但并未从 threading.enumerate() 中删除。如果我在其引用上调用 isAlive(),它会 returns False。我试过如果一个线程的 run() 方法 returns 正常,那个线程应该从那个列表中删除。

这很糟糕,因为如果线程仍然引用那个 Thread 对象,理论上它的资源将不会被收集,最终可能导致内存泄漏。

在线程上执行 _Thread__stop 后,我应该怎么做才能确保清理干净?

扩展我的评论,没有人相信这个 ;-),所以这里有一些代码 显示 它(仅 Python 2):

from time import sleep
import threading

def f():
    while True:
        print("running")
        sleep(1)

t = threading.Thread(target=f)
print("starting thread")
t.start()
sleep(.5)
print("'stopping' thread")
t._Thread__stop()
sleep(2)
print("huh! thread is still running")
sleep(10)

并且输出:

starting thread
running
'stopping' thread
running
running
huh! thread is still running
running
running
running
running
running
running
running
running
running
running

_Thread__stop 对停止线程毫无用处(threading 中没有其他内容可以强制线程停止)。

调用它 的作用是将 threading 的内部结构置于混乱状态。在这种情况下,因为 ._stop() 被错误地调用了 threading 的其他部分 相信 线程已经停止,所以 Python 在最后的睡眠后愉快地退出尽管非守护线程 t 仍然是 运行.

但这不是错误:您使用私有的、未记录的方法(如 ._stop())需要您自担风险。