【发布时间】:2020-06-14 15:32:30
【问题描述】:
当我将线程定义为实例变量时,定义的其他对象不会被垃圾回收。在此示例中,在循环的每次迭代中都会创建一个数组 buffer,该数组永远不会被垃圾回收:
import array
import gc
import threading
from pympler import muppy
class A():
def __init__(self):
self.buffer = array.array('B')
# Defining a thread keeps array in memory
self.thread = threading.Thread(target=lambda *_: None)
if __name__ == '__main__':
for i in range(10):
a = A()
# del a # needed
gc.collect()
print('Iteration {}:'.format(i))
obj = muppy.get_objects()
print('Array objects {}'.format(len(muppy.filter(obj, Type=array.ArrayType))))
print('Thread objects {}'.format(len(muppy.filter(obj, Type=threading.Thread))))
print('Running threads {}'.format(len(threading.enumerate())))
输出是:
Iteration 0:
Array objects 1
Thread objects 2
Running threads 1
Iteration 1:
Array objects 2
Thread objects 3
Running threads 1
...
线程是否启动+加入无关紧要。 显式删除对象 buffer 或 self.thread 允许垃圾回收。我无法理解这种行为,并希望得到一些解释。 在我的生产代码中,此功能最终会导致 python 实例的内存不足终止。
【问题讨论】:
标签: python multithreading memory-leaks garbage-collection