python / python/cpython

Add a private API to defer automatic garbage collection

未关闭
#153,946 10 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

interpreter-core type-feature
主要语言
Python
星标
77.2k
派生
35.9k
PR 合并指标
PR 指标待抓取

描述

I would like to propose a private API that allows CPython internals to defer automatic garbage collection on the current thread without changing the interpreter-visible GC state.

Some CPython internals build large object graphs in a burst, where a collection triggered halfway through cannot reclaim anything from that operation and only traverses a half-built graph. Using PyGC_Disable() for this changes interpreter-wide state. Saving and restoring that state is racy in the free-threaded build, and it can also be observed or changed by user code in the GIL build.

What we want is something approximately like:

_PyGC_DeferAutomaticCollection(tstate);
/* Build a large object graph. */
_PyGC_ResumeAutomaticCollection(tstate);

This would be a private CPython API. It should be per-thread and nestable, keep allocation counters running, leave gc.isenabled() unchanged, and defer only automatic collection. Leaving the outermost scope would schedule a collection if one became due.

I think there are many possible cases in the stdlib and core that can benefit from this, and we currently do not have a safe tool for them. This can be implemented with a small nesting counter in _PyThreadStateImpl, checked by the allocation paths and _Py_RunGC(). This would allow these optimizations without changing user-visible GC state or introducing cross-thread races.

Linked PRs
  • gh-154188

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

首先检查 _PyThreadStateImpl、分配路径和 _Py_RunGC(),提案将它们确定为相关的入口点。实现应满足每个线程的嵌套,保留分配计数器和 gc.isenabled(),仅推迟自动回收,并在最外层作用域恢复时安排一次已到期的回收。

由索引模型根据 Issue 内容生成。

评估

技术栈
c, python
领域
backend
Issue 类型
功能
难度
5/5
预计耗时
一周以上
活跃度
停滞
描述清晰度
基本清楚
新手友好度
25/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。