gpt4 book ai didi

Python 线程垃圾回收

转载 作者:太空狗 更新时间:2023-10-29 22:23:54 26 4
gpt4 key购买 nike

如果线程对象被重新分配,正在运行的线程是否有资格进行垃圾回收?例如:

class A(threading.Thread)
def run():
while True:
#Do stuff


a = A()
a.start()
time.sleep(60)
a = A()

此时,即使线程 A 仍在执行操作,解释器是否可以销毁原始的 A() 线程?如果是,是否有办法防止这种情况发生?

最佳答案

我的猜测是否定的。在 Python 用来跟踪事物的任何结构中仍然有对线程的引用。我会测试它,但如果它不起作用,我会感到很惊讶。

编辑检查一下:

#!/usr/bin/env python
import threading, time

class A(threading.Thread):
def __init__(self, name):
threading.Thread.__init__(self)
self.name=name
self.count=0
def run(self):
while self.count<10:
print self.name, "Running!"
time.sleep(1)
self.count+=1

a=A("first")
a.start()
time.sleep(5)
a=A("second")
a.start()
first Running!first Running!first Running!first Running!first Running!second Running!first Running!second Running!first Running!first Running!second Running!first Running!second Running!first Running!second Running!second Running!second Running!second Running!second Running!second Running!

关于Python 线程垃圾回收,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4494832/

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