[3.14] gh-137433: Fix deadlock with stop-the-world and daemon threads (gh-137735) (GH-138965)

There was a deadlock originally seen by Memray when a daemon thread
enabled or disabled profiling while the interpreter was shutting down.
I think this could also happen with garbage collection, but I haven't
seen that in practice.

The daemon thread could be hung while trying acquire the global rwmutex
that prevents overlapping global and per-interpreter stop-the-world events.
Since it already held the main interpreter's stop-the-world lock, it
also deadlocked the main thread, which is trying to perform interpreter
finalization.

Swap the order of lock acquisition to prevent this deadlock.
Additionally, refactor `_PyParkingLot_Park` so that the global buckets
hashtable is left in a clean state if the thread is hung in
`PyEval_AcquireThread`.

(cherry picked from commit 90fe3250f8)

Co-authored-by: Sam Gross <colesbury@gmail.com>
This commit is contained in:
Miss Islington (bot) 2025-10-07 20:46:52 +02:00 committed by GitHub
parent db8b943259
commit e09f33e5bf
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 51 additions and 4 deletions

View file

@ -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.