]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-136870: fix data race in `PyThreadState_Clear` on `sys_tracing_threads` (#136951)
authorKumar Aditya <kumaraditya@python.org>
Mon, 21 Jul 2025 20:35:25 +0000 (02:05 +0530)
committerGitHub <noreply@github.com>
Mon, 21 Jul 2025 20:35:25 +0000 (20:35 +0000)
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.

Python/pystate.c

index 0d4c26f92cec909dd8c873d998545ddf7647b2ec..04ca6edb4aaa0ebc19fddc36bb8b33f549f1bef9 100644 (file)
@@ -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);