Python 守护线程内存泄漏?

Python Daemon Thread Memory Leak?

如果我在Python (3.6+) 中创建了一个守护线程并且该守护线程执行完毕,它的资源是自动释放的,还是内存泄漏?我环顾四周找不到真正的答案...我认为它已被释放但偏执并希望有人可以澄清。

我做了一个基本的例子:

import threading
import time

class Processor():
    
    def get_data_in_thread(self, id):
        for i in range(3):
            time.sleep(1)
            print(f'{id} count: {i}')

        #at this point is this thread's resources automatically garbage collected? Or is this a memory leak?

    def get_data(self, id):
        t = threading.Thread(target=self.get_data_in_thread, args=(id,))
        t.daemon = True
        t.start()


my_processor = Processor()
my_processor.get_data(17)

time.sleep(30)

当守护线程内部的工作在get_data_in_thread完成时 在该线程中分配的内存是否自动释放,或者是否有一个特定的命令我可以用来自行终止它自己的守护进程线程?像 del() 或类似的?

谢谢!

当一个线程被销毁时,就像任何其他对象一样,如果它不再被引用(refcount 变为 0),它会立即被收集。线程引用的所有资源也是如此,在您的情况下是内部函数变量,因为它们没有在其他任何地方被引用。

您必须调用 thread.join() 才能完全将其标记为符合垃圾回收条件。
如果你想在它加入后立即释放它的所有内存,那么执行 gc.collect().