Repeated Python Thread State creation and destruction for foreign threads is slow
還沒有人認領這個 Issue。
- 主要語言
- Python
- 星號
- 77.2k
- 分支
- 36k
- 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
貢獻指南
從這裡開始
- 先讀完整個 Issue,再讀專案的貢獻指南。
- 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
- Fork 儲存庫,在一個分支上完成修改。
- 送出 Pull Request,並在描述裡引用這個 Issue 編號。
研究方向
先檢視 gh-146221 和 gh-152644 中連結的工作,接著追蹤此 issue 中描述的 PyGILState_Ensure() 和 PyGILState_Release() 行為。完成這項工作需要就減少外部執行緒狀態的重複建立與銷毀達成共識,並驗證其效能與正確性。
由索引模型根據 Issue 內容生成。
評估
- 技術堆疊
- c, python
- 領域
- api, backend
- Issue 類型
- 功能
- 難度
- 5/5
- 預估耗時
- 一週以上
- 活躍度
- 停滯
- 描述清晰度
- 需要釐清
- 新手友好度
- 20/100