在Python中,以currentThread()为键的字典会导致内存泄漏吗?
我正在调试 Django 应用程序中的内存泄漏,并且 django_cachepurge 中可能有一些奇怪的事情:
from threading import currentThread
_urls_to_purge = {}
def add_purge_url(url):
# ....
_urls_to_purge.setdefault(currentThread(), set()).add(url)
这样的构造容易发生内存泄漏吗? 我怀疑是这样,除非我不熟悉这里的一些 Python 魔法。 没有清理字典的位置。
I'm debugging memory leaks in a Django application, and could something curious in django_cachepurge
:
from threading import currentThread
_urls_to_purge = {}
def add_purge_url(url):
# ....
_urls_to_purge.setdefault(currentThread(), set()).add(url)
Is such construct prone to memory leaks?
I suspect so, unless I'm not familiar with some Python magic here.
There is no location where the dict is cleaned up.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不知道
currentThread
返回什么,但您可能可以使用内置的id
或hash
函数来获取安全值。如果查找还不够,例如因为您想迭代容器,则可以使用
weakref.WeakKeyDictionary
。I don't know what
currentThread
returns, but you probably can use the built-inid
orhash
functions on it to get a safe value.If lookup isn't enough, e.g. because you want to iterate over the container, there is
weakref.WeakKeyDictionary
.