Python线程垃圾收集

前端之家收集整理的这篇文章主要介绍了Python线程垃圾收集前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如果重新分配线程对象,是否正在运行的线程可以进行垃圾回收?例如:
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相关文章