Python线程垃圾收集

时间:2010-12-20 22:58:26

标签: python multithreading garbage-collection

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

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


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

此时,即使线程A仍然在做东西,解释器是否可以破坏原始的A()线程?如果确实如此,有没有办法防止这种情况发生?

3 个答案:

答案 0 :(得分:5)

我的猜测是否定的。在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!

答案 1 :(得分:3)

线程不会被删除,但我猜你遇到的问题是线程无缘无故地消失了?未处理的异常会在不影响主线程的情况下终止线程!它只将回溯打印到stderr,但你可能看不到......

答案 2 :(得分:1)

如果对某个地方的对象有引用,则线程不会被垃圾收集。

参见https://hg.python.org/cpython/file/2.7/Lib/threading.py,它会密切关注线程对象。

# Active thread administration
_active_limbo_lock = _allocate_lock()
_active = {}    # maps thread id to Thread object
_limbo = {}

threading模块保留模块变量中的引用。当你致电threading.enumerate()时,你正在迭代相同的变量。

当你致电start()时,它会在模块变量中插入对Thread对象的引用,当run()终止时,它会清除引用。