代码成就万世基积沙镇海,梦想永在凌云意意气风发。

Python3.5源码分析-垃圾回收机制

Python3的垃圾回收概述

随着软硬件的发展,大多数语言都已经支持了垃圾回收机制,让使用者从内存管理的工作中解放出来。Python的垃圾回收机制,采用了引用计数来管理的,引用计数也算是一种垃圾回收机制,也是一种直观简单的垃圾回收计数,引用计数方法的优点即实时性,当引用计数为0时,就可以立即回收。引用计数有一个致命的弱点那就是循环引用。

循环引用

引用计数的机制相对简单,当一个对象被创建或复制时,对象的引用计数加1,当一个对象的引用被销毁时,对象的引用计数减1,如果对象的引用计数减少到0,则会启动垃圾回收机制将其回收。但是,循环引用可以使一组对象的引用计数都不为0,然而这些对象实际上并没有任何外部变量引用,它们之间只是相互引用,这时候意味着如果不使用这组对象,应该回收这些对象所占用的内存,然而由于此时的引用计数都不为0,这些对象所占用的内存都不会被回收。

为了解决这个问题,Python引入了主力垃圾收集技术中的标记-清除分代收集两种技术来填充其内存管理机制的弱点。

标记-清除的简要工作流程如下:1.寻找根对象的集合,根对象就是一些全局引用和函数栈中的引用;2.从根对象集合出发,沿着根对象集合中的每一个引用,如果能达到某个对象A,则A称为可到达的,可到达的对象不可被删除,这就是垃圾检测阶段;3.当垃圾检测结束后,所有的对象分为了可到达的和不可到达的两部分,可到达的要予以保留,而不可到达的对象所占用的内存将被回收,这就是垃圾回收阶段。这就是标记-清除的大致工作流程。

在Python中,由于循环引用是当可被引用的对象之间才会出现,所以Python中需要检查的对象就是可被其他对象所引用的对象,例如list、dict、class等可被引用的对象,像int、str等不引用其他对象的类型则不需要被检查,因此Python中的垃圾回收主要就是回收这些能被引用的对象,为了达到这一点Python在创建这些对象的时候就会把这些对象加入到一个可收集的对象链表中。

分代的垃圾回收机制,主要是通过研究表明,对于不同的语言,不同的应用程序,一些内存块的生存周期相对持续比较长,在这种情况下,当需回收的内存块越多时,垃圾检测带来的额外操作就越多,而垃圾回收带来的额外操作就越少,反之,当需要回收的内存块越少时,垃圾检测就将比垃圾回收带来更少的额外操作。为了使垃圾回收的效率提高,基于研究人员的统计规律,就出现了一种以空间换时间的策略,将系统中的所有内存块根据其存活时间划分为不同的集合,每一个集合就称为一代,垃圾收集的频率随着代的存活时间的增大而减少,也就是说,活的越长的对象,就越不可能是垃圾,就应该少去收集,通常利用经过了几次垃圾收集动作来衡量,如果一个对象经过的垃圾收集次数越多,其存货时间就越长。例如,当某些内存块A经历了多次的垃圾收集之后仍然还不被释放,就将A划分到集合L1中,而新分配的内存都划分到集合L2中,当垃圾收集开始工作时,大多数情况都只对集合L2进行垃圾回收,对L1则等一段时间后再进行回收,这就使垃圾收集需要处理的内存变少了,效率则得到提高,在集合L2中的内存块再经历了多次收集之后仍然存活,则将其划分到L1中去,诚然在L1中确实是有一些需要回收的垃圾,但是这需要等过一段时间才会被收集,所以这就是一种空间换时间的策略。

在Python中使用的分代垃圾回收机制,总共分为三个代,一个代就是代表一代可收集对象的对象链表。

Python垃圾回收的执行过程(如有问题依据官方文档为准,仅限个人理解)

在Python中,由于使用了标记-清除和分代的两种作为引用计数的补充,我们就从list的过程来分析这一过程的执行。

首先,在list的初始化生成过程中,会调用list的tp_alloc方法去申请内存,此时list对应的tp_alloc方法为PyType_GenericAlloc,

 1 PyObject *
 2 PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
 3 {
 4     PyObject *obj;
 5     const size_t size = _PyObject_VAR_SIZE(type, nitems+1);             // 获取生成的字节大小
 6     /* note that we need to add one, for the sentinel */
 7 
 8     if (PyType_IS_GC(type))                                             // 判断type是否是需要GC的类型
 9         obj = _PyObject_GC_Malloc(size);                                // 加入收集列表并申请内存
10     else
11         obj = (PyObject *)PyObject_MALLOC(size);                        // 直接申请内存
12 
13     if (obj == NULL)                                                    // 如果返回为空则表示申请内存失败
14         return PyErr_NoMemory();
15 
16     memset(obj, '\0', size);                                            // 将申请到的内存重写'\0'
17 
18     if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
19         Py_INCREF(type);                                                // 引用计数加1
20 
21     if (type->tp_itemsize == 0)
22         (void)PyObject_INIT(obj, type);                                 // 初始化头部
23     else
24         (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);     // 初始化设置相关存在的值
25 
26     if (PyType_IS_GC(type))         
27         _PyObject_GC_TRACK(obj);                                        // 如果是可GC的对象,则加入跟踪链表中
28     return obj;
29 }
View Code

其中,PyType_IS_GC的定义如下,

1 /* Test if a type has a GC head */
2 #define PyType_IS_GC(t) PyType_HasFeature((t), Py_TPFLAGS_HAVE_GC)
3 ...
4 #define PyType_HasFeature(t,f)  (((t)->tp_flags & (f)) != 0)
View Code

就是判断这个类型的tp_flags是否拥有传入的type类型。

此时如果是GC对象,则调用_PyObject_GC_Malloc函数去申请内存,带哦用了位于gcmodule.c中的该函数,

1 PyObject *
2 _PyObject_GC_Malloc(size_t basicsize)
3 {
4     return _PyObject_GC_Alloc(0, basicsize);
5 }
View Code

调用了位于gcmodule.c的_PyObject_GC_Alloc函数,

 1 static PyObject *
 2 _PyObject_GC_Alloc(int use_calloc, size_t basicsize)
 3 {
 4     PyObject *op;
 5     PyGC_Head *g;
 6     size_t size;
 7     if (basicsize > PY_SSIZE_T_MAX - sizeof(PyGC_Head))         
 8         return PyErr_NoMemory();
 9     size = sizeof(PyGC_Head) + basicsize;                     // 申请内存的大小要包括PyGC_Head和申请的basicsize大小
10     if (use_calloc)
11         g = (PyGC_Head *)PyObject_Calloc(1, size);            // 申请内存
12     else
13         g = (PyGC_Head *)PyObject_Malloc(size);
14     if (g == NULL)
15         return PyErr_NoMemory();
16     g->gc.gc_refs = 0;                                        // 设置引用计数的副本
17     _PyGCHead_SET_REFS(g, GC_UNTRACKED);                      // 设置g为GC_UNTRACKED
18     generations[0].count++; /* number of allocated GC objects */   // 第一代总数值加1
19     if (generations[0].count > generations[0].threshold &&
20         enabled &&
21         generations[0].threshold &&
22         !collecting &&
23         !PyErr_Occurred()) {                                  // 如果第一代的计数值大于第一代的阈值
24         collecting = 1;
25         collect_generations();                                // 调用分代处理函数
26         collecting = 0;
27     }
28     op = FROM_GC(g);                                          // 跳过PyGC_Head头部的位置,指向剩余空闲的地址
29     return op;
30 }
View Code

该函数中,PyGC_Head结构就是可收集对象链表的头部位置,

 1 /* GC information is stored BEFORE the object structure. */
 2 #ifndef Py_LIMITED_API
 3 typedef union _gc_head {
 4     struct {
 5         union _gc_head *gc_next;        // 上一个gc
 6         union _gc_head *gc_prev;        // 下一个gc
 7         Py_ssize_t gc_refs;             // gc_refs引用计数值的副本
 8     } gc;
 9     double dummy;  /* force worst-case alignment */
10 } PyGC_Head;
View Code

在每一个可GC的对象的头部都会申请出该PyGC_Head,用来记录该链表。

此时作为一个可GC的对象,对调用_PyObject_GC_TRACK来添加到链表中,

 1 /* Tell the GC to track this object.  NB: While the object is tracked the
 2  * collector it must be safe to call the ob_traverse method. */
 3 #define _PyObject_GC_TRACK(o) do { \
 4     PyGC_Head *g = _Py_AS_GC(o); \                      // 调到GC_HEAD的头部信息
 5     if (_PyGCHead_REFS(g) != _PyGC_REFS_UNTRACKED) \    // 判断是否已经跟踪了
 6         Py_FatalError("GC object already tracked"); \
 7     _PyGCHead_SET_REFS(g, _PyGC_REFS_REACHABLE); \      // 设置g为可到达的
 8     g->gc.gc_next = _PyGC_generation0; \                // 将_PyGC_generation0的第一个位置设置到当前gc的next
 9     g->gc.gc_prev = _PyGC_generation0->gc.gc_prev; \    // 设置当前gc的上一个是_PyGC_generation0的上一个
10     g->gc.gc_prev->gc.gc_next = g; \                    // 设置上一个的下一个为g
11     _PyGC_generation0->gc.gc_prev = g; \                // 设置_PyGC_generation0的上一个为g
12     } while (0);
View Code

此时就将生成的对象加入到了第一代的链表中,其中第一代、第二代和第三代的相关定义如下;

 1 /*** Global GC state ***/
 2 
 3 struct gc_generation {
 4     PyGC_Head head; 
 5     int threshold; /* collection threshold */
 6     int count; /* count of allocations or collections of younger
 7                   generations */
 8 };
 9 
10 #define NUM_GENERATIONS 3
11 #define GEN_HEAD(n) (&generations[n].head)
12 
13 /* linked lists of container objects */
14 static struct gc_generation generations[NUM_GENERATIONS] = {
15     /* PyGC_Head,                               threshold,      count */ 
16     {{{GEN_HEAD(0), GEN_HEAD(0), 0}},           700,            0},       // 第一代阈值是700
17     {{{GEN_HEAD(1), GEN_HEAD(1), 0}},           10,             0},       // 第二代的阈值是10
18     {{{GEN_HEAD(2), GEN_HEAD(2), 0}},           10,             0},       // 第三代的阈值是10
19 };
20 
21 PyGC_Head *_PyGC_generation0 = GEN_HEAD(0);                               // _PyGC_generation0为第一代数组值
View Code

如果此时在申请内存时,第一代的对象大于默认700的阈值,此时就会执行如下,

1 if (generations[0].count > generations[0].threshold &&
2     enabled &&
3     generations[0].threshold &&
4     !collecting &&
5     !PyErr_Occurred()) {                                  // 如果第一代的计数值大于第一代的阈值
6     collecting = 1;
7     collect_generations();                                // 调用分代处理函数
8     collecting = 0;
9 }
View Code

此时就会调用collect_generations函数进行处理,

 1 static Py_ssize_t
 2 collect_generations(void)
 3 {
 4     int i;
 5     Py_ssize_t n = 0;
 6 
 7     /* Find the oldest generation (highest numbered) where the count
 8      * exceeds the threshold.  Objects in the that generation and
 9      * generations younger than it will be collected. */
10     for (i = NUM_GENERATIONS-1; i >= 0; i--) {                        // 从第三代开始往下分代
11         if (generations[i].count > generations[i].threshold) {        // 如果当前这一代超过了阈值
12             /* Avoid quadratic performance degradation in number
13                of tracked objects. See comments at the beginning
14                of this file, and issue #4074.
15             */
16             if (i == NUM_GENERATIONS - 1
17                 && long_lived_pending < long_lived_total / 4)
18                 continue;
19             n = collect_with_callback(i);                             // 调用该函数进行分代
20             break;
21         }
22     }
23     return n;
24 }
View Code

此时就会找到最老的那一代满足收集条件的进行collect_with_callback函数操作,

 1 /* Perform garbage collection of a generation and invoke
 2  * progress callbacks.
 3  */
 4 static Py_ssize_t
 5 collect_with_callback(int generation)
 6 {
 7     Py_ssize_t result, collected, uncollectable;
 8     invoke_gc_callback("start", generation, 0, 0);
 9     result = collect(generation, &collected, &uncollectable, 0);          // 调用collect进行操作
10     invoke_gc_callback("stop", generation, collected, uncollectable);
11     return result;
12 }
View Code

此时就会调用collect函数进行操作,有关collect的函数就是垃圾回收的所有的操作的流程都在这个流程中实现,其代码如下;

  1 /* This is the main function.  Read this to understand how the
  2  * collection process works. */
  3 static Py_ssize_t
  4 collect(int generation, Py_ssize_t *n_collected, Py_ssize_t *n_uncollectable,
  5         int nofail)
  6 {
  7     int i;
  8     Py_ssize_t m = 0; /* # objects collected */
  9     Py_ssize_t n = 0; /* # unreachable objects that couldn't be collected */
 10     PyGC_Head *young; /* the generation we are examining */
 11     PyGC_Head *old; /* next older generation */
 12     PyGC_Head unreachable; /* non-problematic unreachable trash */
 13     PyGC_Head finalizers;  /* objects with, & reachable from, __del__ */
 14     PyGC_Head *gc;
 15     _PyTime_t t1 = 0;   /* initialize to prevent a compiler warning */
 16 
 17     struct gc_generation_stats *stats = &generation_stats[generation];
 18 
 19     if (debug & DEBUG_STATS) {                                          // 如果是调试状态
 20         PySys_WriteStderr("gc: collecting generation %d...\n",
 21                           generation);
 22         PySys_WriteStderr("gc: objects in each generation:");
 23         for (i = 0; i < NUM_GENERATIONS; i++)
 24             PySys_FormatStderr(" %zd",
 25                               gc_list_size(GEN_HEAD(i)));
 26         t1 = _PyTime_GetMonotonicClock();
 27 
 28         PySys_WriteStderr("\n");
 29     }
 30 
 31     /* update collection and allocation counters */
 32     if (generation+1 < NUM_GENERATIONS)                                
 33         generations[generation+1].count += 1;                         // 当前收集次数加1
 34     for (i = 0; i <= generation; i++)
 35         generations[i].count = 0;                                     // 将剩余代数的收集次数设置成0
 36 
 37     /* merge younger generations with one we are currently collecting */
 38     for (i = 0; i < generation; i++) {
 39         gc_list_merge(GEN_HEAD(i), GEN_HEAD(generation));             // 合并年轻一代的链表
 40     }
 41 
 42     /* handy references */
 43     young = GEN_HEAD(generation);                                     // 获取当前传入这一代的对象
 44     if (generation < NUM_GENERATIONS-1)                               // 如果传入的一代小于2
 45         old = GEN_HEAD(generation+1);                                 // old为generation+1
 46     else
 47         old = young;                                                  // 否则old就为自己这一代
 48 
 49     /* Using ob_refcnt and gc_refs, calculate which objects in the
 50      * container set are reachable from outside the set (i.e., have a
 51      * refcount greater than 0 when all the references within the
 52      * set are taken into account).
 53      */
 54     update_refs(young);                                              // 更新引用计数的副本
 55     subtract_refs(young);                                            // 摘除循环引用
 56 
 57     /* Leave everything reachable from outside young in young, and move
 58      * everything else (in young) to unreachable.
 59      * NOTE:  This used to move the reachable objects into a reachable
 60      * set instead.  But most things usually turn out to be reachable,
 61      * so it's more efficient to move the unreachable things.
 62      */
 63     gc_list_init(&unreachable);                                     // 初始化unreachable链表        
 64     move_unreachable(young, &unreachable);                          // 将young中不可到达的移动到unreachable链表上
 65 
 66     /* Move reachable objects to next generation. */
 67     if (young != old) {                                             // 如果young和old不相等则证明还有上一代
 68         if (generation == NUM_GENERATIONS - 2) {                    
 69             long_lived_pending += gc_list_size(young);              // 获取存活长久的对象的大小
 70         }
 71         gc_list_merge(young, old);                                  // 将可到达的设置到老一代
 72     }
 73     else {
 74         /* We only untrack dicts in full collections, to avoid quadratic
 75            dict build-up. See issue #14775. */
 76         untrack_dicts(young);
 77         long_lived_pending = 0;
 78         long_lived_total = gc_list_size(young);                     // 设置存活的总数
 79     }
 80 
 81     /* All objects in unreachable are trash, but objects reachable from
 82      * legacy finalizers (e.g. tp_del) can't safely be deleted.
 83      */
 84     gc_list_init(&finalizers);
 85     move_legacy_finalizers(&unreachable, &finalizers);
 86     /* finalizers contains the unreachable objects with a legacy finalizer;
 87      * unreachable objects reachable *from* those are also uncollectable,
 88      * and we move those into the finalizers list too.
 89      */
 90     move_legacy_finalizer_reachable(&finalizers);
 91 
 92     /* Collect statistics on collectable objects found and print
 93      * debugging information.
 94      */
 95     for (gc = unreachable.gc.gc_next; gc != &unreachable;
 96                     gc = gc->gc.gc_next) {
 97         m++;
 98         if (debug & DEBUG_COLLECTABLE) {
 99             debug_cycle("collectable", FROM_GC(gc));
100         }
101     }
102 
103     /* Clear weakrefs and invoke callbacks as necessary. */
104     m += handle_weakrefs(&unreachable, old);                    // 处理弱引用相关
105 
106     /* Call tp_finalize on objects which have one. */
107     finalize_garbage(&unreachable);                             // 调用含有__del__方法的对象进行释放
108 
109     if (check_garbage(&unreachable)) {                          // 检查所有的是否是不可达到的
110         revive_garbage(&unreachable);                           // 设置列表中的为可到达的
111         gc_list_merge(&unreachable, old);                       // 合并可到达的到old列表中
112     }
113     else {
114         /* Call tp_clear on objects in the unreachable set.  This will cause
115          * the reference cycles to be broken.  It may also cause some objects
116          * in finalizers to be freed.
117          */
118         delete_garbage(&unreachable, old);                      // 对unreachable进行垃圾回收
119     }
120 
121     /* Collect statistics on uncollectable objects found and print
122      * debugging information. */
123     for (gc = finalizers.gc.gc_next;                            // 打印相关调试信息
124          gc != &finalizers;
125          gc = gc->gc.gc_next) {
126         n++;
127         if (debug & DEBUG_UNCOLLECTABLE)
128             debug_cycle("uncollectable", FROM_GC(gc));
129     }
130     if (debug & DEBUG_STATS) {
131         _PyTime_t t2 = _PyTime_GetMonotonicClock();
132 
133         if (m == 0 && n == 0)
134             PySys_WriteStderr("gc: done");
135         else
136             PySys_FormatStderr(
137                 "gc: done, %zd unreachable, %zd uncollectable",
138                 n+m, n);
139         PySys_WriteStderr(", %.4fs elapsed\n",
140                           _PyTime_AsSecondsDouble(t2 - t1));
141     }
142 
143     /* Append instances in the uncollectable set to a Python
144      * reachable list of garbage.  The programmer has to deal with
145      * this if they insist on creating this type of structure.
146      */
147     (void)handle_legacy_finalizers(&finalizers, old);                 // 将unreachable但拥有finalizers放入  garbage列表中,并将finalizers合并入old中
148 
149     /* Clear free list only during the collection of the highest
150      * generation */
151     if (generation == NUM_GENERATIONS-1) {
152         clear_freelists();
153     }
154 
155     if (PyErr_Occurred()) {
156         if (nofail) {
157             PyErr_Clear();
158         }
159         else {
160             if (gc_str == NULL)
161                 gc_str = PyUnicode_FromString("garbage collection");
162             PyErr_WriteUnraisable(gc_str);
163             Py_FatalError("unexpected exception during garbage collection");
164         }
165     }
166 
167     /* Update stats */
168     if (n_collected)
169         *n_collected = m;
170     if (n_uncollectable)
171         *n_uncollectable = n;
172     stats->collections++;
173     stats->collected += m;
174     stats->uncollectable += n;
175     return n+m;
176 }
View Code

在该函数中,还有对弱引用的处理,在弱引用的配置中还涉及到一些callback的调用,当带有del的对象如果是不可达的,则存入一个garbage的列表中,在其中比较重要的就是将相关的分代对象进行归类合并,然后进过标记清除的过程后,查找出需要释放回收的内存对象,一般情况下当该对象的引用计数为0 的时候就已经通过引用计数机制,被释放掉了,而引用计数不为0的对象一般是被程序使用的对象,或者循环引用中的对象。

其中,有关释放资源的操作delete_garbage执行流程如下;

 1 /* Break reference cycles by clearing the containers involved.  This is
 2  * tricky business as the lists can be changing and we don't know which
 3  * objects may be freed.  It is possible I screwed something up here.
 4  */
 5 static void
 6 delete_garbage(PyGC_Head *collectable, PyGC_Head *old)
 7 {
 8     inquiry clear;
 9 
10     while (!gc_list_is_empty(collectable)) {
11         PyGC_Head *gc = collectable->gc.gc_next;
12         PyObject *op = FROM_GC(gc);                           // 跳过gc的头部指针空间
13 
14         if (debug & DEBUG_SAVEALL) {                          // 如果是调试状态
15             PyList_Append(garbage, op);
16         }
17         else {
18             if ((clear = Py_TYPE(op)->tp_clear) != NULL) {    // 调用op的tp_clear方法去释放资源
19                 Py_INCREF(op);
20                 clear(op);                                    // 执行tp_clear方法
21                 Py_DECREF(op);
22             }
23         }
24         if (collectable->gc.gc_next == gc) {                  // 如果释放完成后还是在
25             /* object is still alive, move it, it may die later */
26             gc_list_move(gc, old);                            // 添加到old列表中
27             _PyGCHead_SET_REFS(gc, GC_REACHABLE);             // 设置gc为可到达的
28         }
29     }
30 }
View Code

在处理最后对当前不可处理的garbage则调用了handle_legacy_finalizers来处理该列表,将带有del属性的添加到garbage列表,没有的则重新合并到old列表中,

 1 /* Handle uncollectable garbage (cycles with tp_del slots, and stuff reachable
 2  * only from such cycles).
 3  * If DEBUG_SAVEALL, all objects in finalizers are appended to the module
 4  * garbage list (a Python list), else only the objects in finalizers with
 5  * __del__ methods are appended to garbage.  All objects in finalizers are
 6  * merged into the old list regardless.
 7  * Returns 0 if all OK, <0 on error (out of memory to grow the garbage list).
 8  * The finalizers list is made empty on a successful return.
 9  */
10 static int
11 handle_legacy_finalizers(PyGC_Head *finalizers, PyGC_Head *old)
12 {
13     PyGC_Head *gc = finalizers->gc.gc_next;
14 
15     if (garbage == NULL) {                                          // 如果garbage为NULL
16         garbage = PyList_New(0);                                    // 初始化garbage为一个列表
17         if (garbage == NULL)
18             Py_FatalError("gc couldn't create gc.garbage list");
19     }
20     for (; gc != finalizers; gc = gc->gc.gc_next) {
21         PyObject *op = FROM_GC(gc);
22 
23         if ((debug & DEBUG_SAVEALL) || has_legacy_finalizer(op)) {  // 如果是调试模式或者op的__del__不为空
24             if (PyList_Append(garbage, op) < 0)                     // 添加到该列表中
25                 return -1;
26         }
27     }
28 
29     gc_list_merge(finalizers, old);                                 // 将剩余的合并到old中
30     return 0;
31 }
View Code

打破循环引用通过清零containers,但是根据注释可知,这也可能引起其他问题。

在处理最后对当前不可处理的garbage则调用了handle_legacy_finalizers来处理该列表,将带有del属性的添加到garbage列表,没有的则重新合并到old列表中,

 1 /* Handle uncollectable garbage (cycles with tp_del slots, and stuff reachable
 2  * only from such cycles).
 3  * If DEBUG_SAVEALL, all objects in finalizers are appended to the module
 4  * garbage list (a Python list), else only the objects in finalizers with
 5  * __del__ methods are appended to garbage.  All objects in finalizers are
 6  * merged into the old list regardless.
 7  * Returns 0 if all OK, <0 on error (out of memory to grow the garbage list).
 8  * The finalizers list is made empty on a successful return.
 9  */
10 static int
11 handle_legacy_finalizers(PyGC_Head *finalizers, PyGC_Head *old)
12 {
13     PyGC_Head *gc = finalizers->gc.gc_next;
14 
15     if (garbage == NULL) {                                          // 如果garbage为NULL
16         garbage = PyList_New(0);                                    // 初始化garbage为一个列表
17         if (garbage == NULL)
18             Py_FatalError("gc couldn't create gc.garbage list");
19     }
20     for (; gc != finalizers; gc = gc->gc.gc_next) {
21         PyObject *op = FROM_GC(gc);
22 
23         if ((debug & DEBUG_SAVEALL) || has_legacy_finalizer(op)) {  // 如果是调试模式或者op的__del__不为空
24             if (PyList_Append(garbage, op) < 0)                     // 添加到该列表中
25                 return -1;
26         }
27     }
28 
29     gc_list_merge(finalizers, old);                                 // 将剩余的合并到old中
30     return 0;
31 }
View Code

当引用计数为0时,则直接就释放了该对象,

1 #define Py_DECREF(op)                                   \
2     do {                                                \
3         PyObject *_py_decref_tmp = (PyObject *)(op);    \
4         if (_Py_DEC_REFTOTAL  _Py_REF_DEBUG_COMMA       \
5         --(_py_decref_tmp)->ob_refcnt != 0)             \       // 检查引用计数是否为0 
6             _Py_CHECK_REFCNT(_py_decref_tmp)            \
7         else                                            \
8         _Py_Dealloc(_py_decref_tmp);                    \       // 引用计数为0 则直接释放
9     } while (0)
View Code

总结

有关Python中的垃圾收集机制,使用了分代和标记清除作为辅助来克服循环引用的缺点,相对而言,关于垃圾回收机制还有更多的细节内容没有继续分析,如有兴趣可参考Python源码剖析这本书,然后对照源码继续分析。

posted @ 2018-01-26 23:50  Tomorrow1  阅读(229)  评论(0)    收藏  举报