Python的垃圾收集器如何检测循环引用? [英] How does Python's Garbage Collector Detect Circular References?

查看:218
本文介绍了Python的垃圾收集器如何检测循环引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解Python的垃圾收集器如何检测循环引用。当我查看文档时,我所看到的只是一个声明,表明检测到循环引用,除非所涉及的对象具有 __ del __ 方法。

如果发生这种情况,我的理解(可能是错误的)是gc模块充当故障保护(我假设)遍历所有分配的内存并释放任何无法访问的块。



Python如何检测&在使用gc模块之前自由循环内存引用?

解决方案

我想我找到了一些我在寻找的答案@SvenMarnich在原始问题的注释中提供的链接:

容器对象是可以保存对其他Python对象的引用的Python对象。列表,类,元组等都是容器对象;整数,字符串等不是。因此,只有容器对象处于循环引用的风险中。



每个Python对象都有一个字段 - * gc_ref *,这是(我相信)设置为NULL对于非容器对象。对于容器对象,它被设置为等于引用它的非容器对象的数量



任何容器对象的* gc_ref *数量大于1(?我会想到0,但现在确定?)的引用不是容器对象。所以它们是可到达的,并且从考虑到不可到达的存储岛被移除。



任何容器对象都可以通过一个已知可达的对象(即那些我们刚刚认为具有* gc_ref * count大于1)也不需要被释放。



剩余的容器对象不可访问(彼此除外),应该被释放。 / p>

http://www.arctrix。 com / nas / python / gc / 是一个提供完整解释的链接
http://hg.python.org/cpython/file/2059910e7d76/Modules/gcmodule.c 是源代码的链接,它的注释进一步解释了循环引用背后的想法检测

I'm trying to understand how Python's garbage collector detects circular references. When I look at the documentation, all I see is a statement that circular references are detected, except when the objects involved have a __del__ method.

If this happens, my understanding (possibly faulty) is that the gc module acts as a failsafe by (I assume) walking through all the allocated memory and freeing any unreachable blocks.

How does Python detect & free circular memory references before making use of the gc module?

解决方案

I think I found the answer I'm looking for in some links provided by @SvenMarnich in comments to the original question:

Container objects are Python objects that can hold references to other Python objects. Lists, Classes, Tuples etc are container objects; Integers, Strings etc. are not. So, only container objects are at risk for being in a circular reference.

Each Python object has a field - *gc_ref*, which is (I believe) set to NULL for non-container objects. For container objects it is set equal to the number of non container objects that reference it

Any container object with a *gc_ref* count greater than 1 (? I would've thought 0, but OK for now ?) has references that are not container objects. So they are reachable and are removed from consideration of being unreachable memory islands.

Any container object reachable by an object known to be reachable (i.e. those we just recognized as having a *gc_ref* count greater than 1) also does not need to be freed.

The remaining container objects are not reachable (except by each other) and should be freed.

http://www.arctrix.com/nas/python/gc/ is a link providing a fuller explanation http://hg.python.org/cpython/file/2059910e7d76/Modules/gcmodule.c is a link to the source code, which has comments further explaining the thoughts behind the circular reference detection

这篇关于Python的垃圾收集器如何检测循环引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆