From: Kumar Aditya Date: Mon, 21 Jul 2025 20:35:25 +0000 (+0530) Subject: gh-136870: fix data race in `PyThreadState_Clear` on `sys_tracing_threads` (#136951) X-Git-Tag: v3.15.0a1~893 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=f183996eb77fd2d5662c62667298c292c943ebf5;p=thirdparty%2FPython%2Fcpython.git 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. --- diff --git a/Python/pystate.c b/Python/pystate.c index 0d4c26f92cec..04ca6edb4aaa 100644 --- a/Python/pystate.c +++ b/Python/pystate.c @@ -1682,6 +1682,10 @@ PyThreadState_Clear(PyThreadState *tstate) "PyThreadState_Clear: warning: thread still has a generator\n"); } +#ifdef Py_GIL_DISABLED + PyMutex_Lock(&_PyRuntime.ceval.sys_trace_profile_mutex); +#endif + if (tstate->c_profilefunc != NULL) { tstate->interp->sys_profiling_threads--; tstate->c_profilefunc = NULL; @@ -1690,6 +1694,11 @@ PyThreadState_Clear(PyThreadState *tstate) tstate->interp->sys_tracing_threads--; tstate->c_tracefunc = NULL; } + +#ifdef Py_GIL_DISABLED + PyMutex_Unlock(&_PyRuntime.ceval.sys_trace_profile_mutex); +#endif + Py_CLEAR(tstate->c_profileobj); Py_CLEAR(tstate->c_traceobj);