gh-151646: Fix data race between gc.get_stats() and GC in free-threading builds#151766
Open
zangjiucheng wants to merge 1 commit into
Open
gh-151646: Fix data race between gc.get_stats() and GC in free-threading builds#151766zangjiucheng wants to merge 1 commit into
zangjiucheng wants to merge 1 commit into
Conversation
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-threading builds,
gc_get_stats_impl()reads per-generation statswith plain struct copies while
gc_collect_main()writes the same fieldsafter
_Py_StartTheWorld()— no synchronisation on either side.Fix: add
PyMutex stats_mutexto_gc_runtime_state(underPy_GIL_DISABLED) and hold it around both the seven field writes in thewriter and the three struct copies in the reader. The lock is acquired after
_Py_StartTheWorld(), so no deadlock with stop-the-world. GIL build isunchanged.
Also adds
Lib/test/test_free_threading/test_gc_get_stats_race.py.Verified with TSAN on Linux: race confirmed on
main, clean on the patch.🤖 Generated with Claude Code
gc.get_stats()and a concurrent collection under free-threading #151646