gh-145235: Make dict watcher API thread-safe for free-threaded builds#145233
Open
yoney wants to merge 3 commits intopython:mainfrom
Open
gh-145235: Make dict watcher API thread-safe for free-threaded builds#145233yoney wants to merge 3 commits intopython:mainfrom
yoney wants to merge 3 commits intopython:mainfrom
Conversation
colesbury
reviewed
Feb 25, 2026
Python/optimizer_analysis.c
Outdated
| PyInterpreterState *interp = _PyInterpreterState_GET(); | ||
| if (interp->dict_state.watchers[GLOBALS_WATCHER_ID] == NULL) { | ||
| interp->dict_state.watchers[GLOBALS_WATCHER_ID] = globals_watcher_callback; | ||
| if (FT_ATOMIC_LOAD_PTR_RELAXED(interp->dict_state.watchers[GLOBALS_WATCHER_ID]) == NULL) { |
Contributor
There was a problem hiding this comment.
A _PyOnceFlag (maybe in JitOptContext) might be a better fit here.
Contributor
Author
There was a problem hiding this comment.
After looking into it (with Claude), JitOptContext seems to be per-optimization-run so _PyOnceFlag might not the right place. I put it in _Py_dict_state as I couldn't find a better place. It fits in the struct packing without extra space.
Contributor
Author
|
@colesbury Thank you for the review. I’ve addressed the comments. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
In free-threaded builds, concurrent calls to
PyDict_AddWatcher,PyDict_ClearWatcher,PyDict_Watch, andPyDict_Unwatchcan race on the shared callback array and the per-dict watcher tags. This change adds a mutex to serialize watcher registration and removal, atomic operations for tag updates, and atomic acquire/release synchronization for callback dispatch in_PyDict_SendEvent.Note: Before this change, running
test.test_free_threading.test_dict_watcheremitted tsan warnings in the free-threaded tsan build.cc: @colesbury @mpage @DinoV