]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-108724: Fix _PySemaphore_Wait call during thread deletion (#116483)
authorSam Gross <colesbury@gmail.com>
Fri, 8 Mar 2024 20:26:36 +0000 (15:26 -0500)
committerGitHub <noreply@github.com>
Fri, 8 Mar 2024 20:26:36 +0000 (15:26 -0500)
In general, when `_PyThreadState_GET()` is non-NULL then the current
thread is "attached", but there is a small window during
`PyThreadState_DeleteCurrent()` where that's not true:
tstate_delete_common() is called when the thread is detached, but before
current_fast_clear().

Co-authored-by: Eric Snow <ericsnowcurrently@gmail.com>
Python/parking_lot.c

index 0a897f9952f648e70ba50b0a53899b6c3a5d2e94..d5877fef56e4d02d06403e37a8654cd24ba8b0e3 100644 (file)
@@ -194,14 +194,16 @@ _PySemaphore_Wait(_PySemaphore *sema, PyTime_t timeout, int detach)
     PyThreadState *tstate = NULL;
     if (detach) {
         tstate = _PyThreadState_GET();
-        if (tstate) {
+        if (tstate && tstate->state == _Py_THREAD_ATTACHED) {
+            // Only detach if we are attached
             PyEval_ReleaseThread(tstate);
         }
+        else {
+            tstate = NULL;
+        }
     }
-
     int res = _PySemaphore_PlatformWait(sema, timeout);
-
-    if (detach && tstate) {
+    if (tstate) {
         PyEval_AcquireThread(tstate);
     }
     return res;