简体   繁体   English

Python线程垃圾收集

[英]Python threads garbage collection

Is a running thread eligable for garbage collection if the thread object is reasigned? 如果重新分配线程对象,是否正在运行的线程可以进行垃圾回收? For example: 例如:

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


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

at this point, even though thread A is still doing stuff, can the interpreter destroy the original A() thread? 在这一点上,即使线程A仍然在做东西,解释器可以破坏原始的A()线程吗? If it does, is there a way to prevent this from happening? 如果确实如此,有没有办法防止这种情况发生?

My guess is no. 我的猜测是否定的。 There's still a reference to the thread in whatever structure Python uses to keep track of things. 在Python用于跟踪事物的任何结构中仍然存在对线程的引用。 I'll test it out, but I'd be astonished if it didn't work. 我会测试它,但如果它不起作用我会感到惊讶。

EDIT Check it out: 编辑检查出来:

#!/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!

Threads wont get deleted like that, but I guess the problem you have is that threads disappear for no reason? 线程不会被删除,但我想你的问题是线程无缘无故地消失了? A unhandled Exception will kill a thread without affecting the main thread! 未处理的Exception会在不影响主线程的情况下终止线程! It only prints the traceback to stderr, but you might not see that ... 它只将回溯打印到stderr,但你可能看不到......

Threads won't get garbage collected if there is a reference to the object kept somewhere. 如果存在对某个地方的对象的引用,则线程不会被垃圾收集。

see https://hg.python.org/cpython/file/2.7/Lib/threading.py , it keeps tabs on thread objects. 请参阅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 = {}

The threading module keeps references in module variables. threading模块在模块变量中保留引用。 When you call threading.enumerate() you are iterating over the same variables. 当你调用threading.enumerate()你正在迭代相同的变量。

When you call start() it inserts a reference to the Thread object in the module variable and when run() terminates, it cleans up the reference. 当你调用start()它会在模块变量中插入对Thread对象的引用,当run()终止时,它会清理引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM