From 68d5fb1ff67683f2dd169a5625777b2a9c71a4a8 Mon Sep 17 00:00:00 2001 From: Sam Gross Date: Thu, 13 Feb 2025 19:38:39 +0000 Subject: [PATCH] gh-130091: Reorder `_PyThreadState_Attach` to avoid data race This moves `tstate_activate()` down to avoid a data race in the free threading build on the `_PyRuntime`'s thread-local `autoTSSkey`. This key is deleted during runtime finalization, which may happen concurrently with a call to `_PyThreadState_Attach`. The earlier `tstate_try/wait_attach` ensures that the thread is blocked before it attempts to access the deleted `autoTSSkey`. This fixes a TSAN reported data race in `test_threading.test_import_from_another_thread`. --- Python/pystate.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Python/pystate.c b/Python/pystate.c index 89a652850e93637..f3e40882f4921e8 100644 --- a/Python/pystate.c +++ b/Python/pystate.c @@ -2090,11 +2090,10 @@ _PyThreadState_Attach(PyThreadState *tstate) // XXX assert(tstate_is_alive(tstate)); current_fast_set(&_PyRuntime, tstate); - tstate_activate(tstate); - if (!tstate_try_attach(tstate)) { tstate_wait_attach(tstate); } + tstate_activate(tstate); #ifdef Py_GIL_DISABLED if (_PyEval_IsGILEnabled(tstate) && !tstate->_status.holds_gil) {