Repeated Python Thread State creation and destruction for foreign threads is slow
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 77.2k
- Forks
- 35.9k
- PR merge metrics
- PR metrics pending
Description
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
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reviewing the linked work in gh-146221 and gh-152644, then trace the PyGILState_Ensure() and PyGILState_Release() behavior described in this issue. Done would require an agreed approach for reducing repeated foreign-thread state creation and destruction, with validation of its performance and correctness.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- c, python
- Domain
- api, backend
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 20/100