gpt4 book ai didi

python - 使用 __del__ 停止 python 线程

转载 作者:太空狗 更新时间:2023-10-30 00:46:37 26 4
gpt4 key购买 nike

我在 Python 中有一个线程程序,它运行良好,除了一旦线程运行后 __del__ 就不会被调用:

class tt(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.stop_event = threading.Event()

def __del__(self):
print "Deleting"
self.stop_event.set()
time.sleep(5)

def run(self):
self.stop_event.clear()
while not self.stop_event.isSet():
self.do_stuff()
threading.Thread.__init__(self)

def stop(self):
self.stop_event.set()

例如,如果我这样做

tc = aa()
del tc

它工作正常(我收到删除消息暂停等)。但是,如果我这样做:

tc = aa()
tc.start()
del tc

然后 __del__ 不会运行(请注意,当我执行 tc.start(); tc.stop(); del tc 时,它会执行 __del__。

我在 ipython 中运行它

最佳答案

__del__() 方法在实例被垃圾回收时执行,而不是在您对恰好指向该实例的名称调用 del 时执行。后者只会删除名称(在某些情况下可能会导致名称指向的实例被 gc'ed)。

当线程仍在运行时,threading.Thread 实例永远不会被垃圾回收,因为在这种情况下该实例仍在使用中。放弃恰好指向实例的名称肯定不会停止线程。

关于python - 使用 __del__ 停止 python 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6928872/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com