python / python/cpython

Repeated Python Thread State creation and destruction for foreign threads is slow

未关闭
#146,219 1 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

docs performance topic-free-threading type-feature
主要语言
Python
星标
77.2k
派生
35.9k
PR 合并指标
PR 指标待抓取

描述

Feature or enhancement

Proposal:

Terminology: foreign thread - An OS thread not created by CPython itself, such as by Rust or C code.

1.) "don't do that" - sure - that's the documentation PR I'll put up to start with, code can manually work around this and improve its performance today. this works on existing Python versions. it matters more on free-threading builds due to their additional allocation overheads but is a meaningful improvement on old-style traditional builds as well.

2.) Simple C API patterns for calling into the CPython interpreter lead to tripping over this performance problem. A classic PyGILState_Ensure() + PyGILState_Release() combo surrounding the call into CPython in a foreign worker thread creates a new Python Thread State via Ensure and destroys it again upon Release. So if you're a foreign thread repeatedly calling into the interpreter (such as a thread pool)... it hurts.

I'm filing this rather than only doing a documentation addition as I think we might be able to make this work smoother by default in many cases without the complications code needs to deal with to prevent it.

One (not well fleshed out) idea to explore - what if we kept a cache of recent ready but no longer referenced thread states for trivial resurrection instead of destroying them upon Release?

Has this already been discussed elsewhere?

No response given

Links to previous discussion of this feature:

No response

Linked PRs
  • gh-146221
  • gh-152644

贡献指南

打开贡献指南

从这里开始

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

调研方向

首先查看 gh-146221 和 gh-152644 中链接的工作,然后跟踪本 issue 中描述的 PyGILState_Ensure() 和 PyGILState_Release() 行为。完成这项工作需要就减少外部线程状态的重复创建和销毁达成一致方案,并验证其性能和正确性。

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

评估

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

把新 issue 发到你的邮箱

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