[Idea][free-threaded][gil_scoped_acquire]: Better Safe Than Sorry (add compat mutex) #5943
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Description
This is a proof-of-concept for discussion, not a final implementation.
The Problem
In traditional Python,
gil_scoped_acquiremeans:In free-threaded Python (
Py_GIL_DISABLED),gil_scoped_acquiremeans:Code written assuming the first meaning is silently broken under free-threading. This includes pybind11 internals and user code.
With pybind11 as-is, free-threading turns every unaudited
gil_scoped_acquireinto a potential data race. Given pybind11's scale of adoption, it's not a question of if these races will bite users, but how many and how badly.I'd much rather hand users a speed limit they can see and choose to remove, than landmines they discover in production.
The Proposal: Better Safe Than Sorry
scoped_ensure_thread_state— just thread state, no lockingThis POC adds a global compatibility mutex that restores the mutual exclusion guarantee for free-threaded builds:
This makes existing code safe by default under free-threading, at the cost of serializing
gil_scoped_acquiresections.Trade-offs
The performance cost is the price of safety, but users who need maximum free-threading performance can migrate to the new helper.
Known Limitation of this POC
The global compat mutex conflicts with per-interpreter GILs (
Py_MOD_PER_INTERPRETER_GIL_SUPPORTED), therefore thePer-Subinterpreter GILtest is skipped under free-threading.Future work could use per-interpreter mutexes instead of a global one.
Questions for Discussion
scoped_ensure_thread_state?