CPython何时收集垃圾? [英] When does CPython garbage collect?

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

问题描述

如果我的理解是正确的,则在CPython对象中,只要其引用计数达到零,它们就会被删除。如果您有无法到达的参考循环,则该逻辑将不起作用,但是有时解释器会尝试找到它们并将其删除(您可以通过调用gc.collect()手动进行此操作)。

If my understanding is correct, in CPython objects will be deleted as soon as their reference count reaches zero. If you have reference cycles that become unreachable that logic will not work, but on occasion the interpreter will try to find them and delete them (and you can do this manually by calling gc.collect() ).

我的问题是,这些解释器触发的循环收集步骤何时发生?

My question is, when do these interpreter-triggered cycle collection steps happen? What kind of events trigger them?

我对CPython案例更感兴趣,但很想听听这在PyPy或其他python实现中有何不同。

I am more interested in the CPython case, but would love to hear how this differs in PyPy or other python implementations.

推荐答案

GC根据自上次GC运行以来发生的分配和解除分配的数量(之间的差值)定期运行。

The GC runs periodically based on the (delta between the) number of allocations and deallocations that have taken place since the last GC run.

请参见 gc.set_threshold()函数


决定何时运行,收集器会跟踪自上次收集以来的对象分配和释放数量。当分配数量减去取消分配数量超过 threshold0 时,收集开始。

您可以访问 gc.get_count()的当前计数code> ;这将返回3个计数的GC记录的元组(其他2个将确定何时进行更深入的扫描)。

You can access the current counts with gc.get_count(); this returns a tuple of the 3 counts GC tracks (the other 2 are to determine when to run deeper scans).

PyPy垃圾收集器的操作完全不同,因为GC PyPy中的进程负责 all 的所有分配,而不仅仅是循环引用。此外,PyPy垃圾收集器是可插入的,这意味着它运行的频率取决于您选择的GC选项。例如,当低于内存阈值时,默认的Minimark策略甚至根本不会运行。

The PyPy garbage collector operates entirely differently, as the GC process in PyPy is responsible for all deallocations, not just cyclic references. Moreover, the PyPy garbage collector is pluggable, meaning that how often it runs depends on what GC option you have picked. The default Minimark strategy doesn't even run at all when below a memory threshold, for example.

请参见 RPython工具链垃圾收集器文档了解有关其策略的一些详细信息,以及 Minimark配置选项,以获得有关可调整内容的更多提示。

See the RPython toolchain Garbage Collector documentation for some details on their strategies, and the Minimark configuration options for more hints on what can be tweaked.

Dyto for Jython或IronPython;这些实现依靠主机运行时(Java和.NET)来处理它们的垃圾回收。

Ditto for Jython or IronPython; these implementations rely on the host runtime (Java and .NET) to handle garbage collection for them.

这篇关于CPython何时收集垃圾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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