Skip to content

gh-151646: Fix data race between gc.get_stats() and GC in free-threading builds#151766

Open
zangjiucheng wants to merge 1 commit into
python:mainfrom
zangjiucheng:gh-151646-fix
Open

gh-151646: Fix data race between gc.get_stats() and GC in free-threading builds#151766
zangjiucheng wants to merge 1 commit into
python:mainfrom
zangjiucheng:gh-151646-fix

Conversation

@zangjiucheng

@zangjiucheng zangjiucheng commented Jun 20, 2026

Copy link
Copy Markdown
Contributor

In free-threading builds, gc_get_stats_impl() reads per-generation stats
with plain struct copies while gc_collect_main() writes the same fields
after _Py_StartTheWorld() — no synchronisation on either side.

Fix: add PyMutex stats_mutex to _gc_runtime_state (under
Py_GIL_DISABLED) and hold it around both the seven field writes in the
writer and the three struct copies in the reader. The lock is acquired after
_Py_StartTheWorld(), so no deadlock with stop-the-world. GIL build is
unchanged.

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

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant