Skip to content

Commit 7aeaa5a

Browse files
authored
gh-130091: Reorder _PyThreadState_Attach to avoid data race (gh-130092)
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`.
1 parent e06bebb commit 7aeaa5a

File tree

1 file changed

+1
-2
lines changed

1 file changed

+1
-2
lines changed

Python/pystate.c

+1-2
Original file line numberDiff line numberDiff line change
@@ -2099,11 +2099,10 @@ _PyThreadState_Attach(PyThreadState *tstate)
20992099

21002100
// XXX assert(tstate_is_alive(tstate));
21012101
current_fast_set(&_PyRuntime, tstate);
2102-
tstate_activate(tstate);
2103-
21042102
if (!tstate_try_attach(tstate)) {
21052103
tstate_wait_attach(tstate);
21062104
}
2105+
tstate_activate(tstate);
21072106

21082107
#ifdef Py_GIL_DISABLED
21092108
if (_PyEval_IsGILEnabled(tstate) && !tstate->_status.holds_gil) {

0 commit comments

Comments
 (0)