Skip to content

gh-146219: Document reusing a thread state across repeated foreign-thread calls#146221

Open
gpshead wants to merge 1 commit intopython:mainfrom
gpshead:gpshead/docs/gilstate-reentrant-performance
Open

gh-146219: Document reusing a thread state across repeated foreign-thread calls#146221
gpshead wants to merge 1 commit intopython:mainfrom
gpshead:gpshead/docs/gilstate-reentrant-performance

Conversation

@gpshead
Copy link
Member

@gpshead gpshead commented Mar 20, 2026

Add a subsection under "Non-Python created threads" explaining the performance cost of creating/destroying a PyThreadState on every Ensure/Release cycle and showing how to keep one alive for the thread's lifetime instead.

(read them & see the issue for more details)


📚 Documentation preview 📚: https://cpython-previews--146221.org.readthedocs.build/

Add a subsection under "Non-Python created threads" explaining the
performance cost of creating/destroying a PyThreadState on every
Ensure/Release cycle and showing how to keep one alive for the
thread's lifetime instead.
@vstinner
Copy link
Member

cc @ZeroIntensity


/* Thread startup: create and pin the state. */
PyGILState_STATE outer = PyGILState_Ensure();
PyThreadState *saved = PyEval_SaveThread();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hm, what's the point of detaching the thread state again? PyGILState_Ensure is able to handle nested calls.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

awaiting core review docs Documentation in the Doc dir performance Performance or resource usage skip news topic-free-threading

Projects

Status: Todo

Development

Successfully merging this pull request may close these issues.

3 participants