python 释放线程内存,关闭Python线程以防止内存泄漏

本文探讨了如何确保Python线程内的所有内存被正确释放的方法。作者最初尝试通过将线程设置为守护进程并调用join来实现这一目标,但发现线程函数内部的对象并未如预期那样被垃圾回收。最终解决方案是将对象从对象函数中移出,放置于常规函数内,以允许垃圾回收机制正常工作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

How to I close a Python thread in order to make sure that everything in memory within a thread is cleared from memory? Currently, I have a list of threads that I join in the following manner:

for t in threadlist:

t.join(5)

These threads were originally created looping over a list of arguments to pass to each thread with myfunc which appends results to a list:

threadlist = []

for r in arglist:

t = Thread(target=myfunc, args=(r,))

t.daemon = True

threadlist.append(t)

When I look at what's in memory with pympler all manner of things in the function called by the thread remain in memory after this executes. I need it to garbage collect as it would if I called myfunc normally without threading.

解决方案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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值