Skip to content

Commit f183996

Browse files
gh-136870: fix data race in PyThreadState_Clear on sys_tracing_threads (#136951)
In free-threading, multiple threads can be cleared concurrently as such the modifications on `sys_tracing_threads` should be done while holding the profile lock, otherwise it can race with other threads setting up profiling.
1 parent 3224429 commit f183996

File tree

1 file changed

+9
-0
lines changed

1 file changed

+9
-0
lines changed

Python/pystate.c

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1682,6 +1682,10 @@ PyThreadState_Clear(PyThreadState *tstate)
16821682
"PyThreadState_Clear: warning: thread still has a generator\n");
16831683
}
16841684

1685+
#ifdef Py_GIL_DISABLED
1686+
PyMutex_Lock(&_PyRuntime.ceval.sys_trace_profile_mutex);
1687+
#endif
1688+
16851689
if (tstate->c_profilefunc != NULL) {
16861690
tstate->interp->sys_profiling_threads--;
16871691
tstate->c_profilefunc = NULL;
@@ -1690,6 +1694,11 @@ PyThreadState_Clear(PyThreadState *tstate)
16901694
tstate->interp->sys_tracing_threads--;
16911695
tstate->c_tracefunc = NULL;
16921696
}
1697+
1698+
#ifdef Py_GIL_DISABLED
1699+
PyMutex_Unlock(&_PyRuntime.ceval.sys_trace_profile_mutex);
1700+
#endif
1701+
16931702
Py_CLEAR(tstate->c_profileobj);
16941703
Py_CLEAR(tstate->c_traceobj);
16951704

0 commit comments

Comments
 (0)