python / python/cpython

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

オープン
#146,219 コメント 1 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

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. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

まず gh-146221 と gh-152644 にリンクされている作業を確認し、次にこの issue で説明されている PyGILState_Ensure() と PyGILState_Release() の動作を追跡します。完了の条件は、外部スレッドの状態が繰り返し作成および破棄されることを削減するための合意されたアプローチがあり、そのパフォーマンスと正しさが検証されていることです。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
c, python
領域
api, backend
issue の種類
機能追加
難易度
5/5
見積もり時間
1週間以上
活発さ
停滞
明瞭さ
説明が足りない
初心者へのやさしさ
20/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。