[3.14] gh-137433: Fix deadlock with stop-the-world and daemon threads (gh-137735) by miss-islington · Pull Request #138965 · python/cpython · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions Lib/test/test_threading.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Fix a potential deadlock in the :term:`free threading` build when daemon
threads enable or disable profiling or tracing while the main thread is
shutting down the interpreter.
19 changes: 17 additions & 2 deletions Python/parking_lot.c
Original file line number Diff line number Diff line change
Expand Up @@ -342,7 +342,19 @@ _PyParkingLot_Park(const void *addr, const void *expected, size_t size,
enqueue(bucket, addr, &wait);
_PyRawMutex_Unlock(&bucket->mutex);

int res = _PySemaphore_Wait(&wait.sema, timeout_ns, detach);
PyThreadState *tstate = NULL;
if (detach) {
tstate = _PyThreadState_GET();
if (tstate && _PyThreadState_IsAttached(tstate)) {
// Only detach if we are attached
PyEval_ReleaseThread(tstate);
}
else {
tstate = NULL;
}
}

int res = _PySemaphore_Wait(&wait.sema, timeout_ns, 0);
if (res == Py_PARK_OK) {
goto done;
}
Expand All @@ -354,7 +366,7 @@ _PyParkingLot_Park(const void *addr, const void *expected, size_t size,
// Another thread has started to unpark us. Wait until we process the
// wakeup signal.
do {
res = _PySemaphore_Wait(&wait.sema, -1, detach);
res = _PySemaphore_Wait(&wait.sema, -1, 0);
} while (res != Py_PARK_OK);
goto done;
}
Expand All @@ -366,6 +378,9 @@ _PyParkingLot_Park(const void *addr, const void *expected, size_t size,

done:
_PySemaphore_Destroy(&wait.sema);
if (tstate) {
PyEval_AcquireThread(tstate);
}
return res;

}
Expand Down
6 changes: 4 additions & 2 deletions Python/pystate.c
Loading