Skip to main content
 首页 » 编程设计

python之关闭 Python 线程以防止内存泄漏

2024年10月01日7kuangbin

如何关闭 Python 线程以确保从内存中清除线程内存中的所有内容?目前,我有一个通过以下方式加入的线程列表:

for t in threadlist: 
    t.join(5) 

这些线程最初创建时循环遍历参数列表以传递给每个线程,myfunc 将结果附加到列表中:

threadlist = [] 
for r in arglist: 
    t = Thread(target=myfunc, args=(r,)) 
    t.daemon = True 
    threadlist.append(t) 

当我使用 pympler 查看内存中的内容时,线程调用的函数中的所有内容在执行后都保留在内存中。我需要它进行垃圾收集,就像我在没有线程的情况下正常调用 myfunc 时一样。

请您参考如下方法:

Resolved in comments:

The objects being deleted were contained within an object function.
Moving them outside of that object function and
into a regular function allowed garbage collecting to occur following delete.
Michael