gh-87135: threading.Lock: Raise rather than hang on Python finalization (GH-135991)

After Python finalization gets to the point where no other thread
can attach thread state, attempting to acquire a Python lock must hang.
Raise PythonFinalizationError instead of hanging.
This commit is contained in:
Petr Viktorin 2025-07-01 10:57:42 +02:00 committed by GitHub
parent 845263adc6
commit fe119a0817
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 97 additions and 5 deletions

View file

@ -95,6 +95,18 @@ _PyMutex_LockTimed(PyMutex *m, PyTime_t timeout, _PyLockFlags flags)
if (timeout == 0) {
return PY_LOCK_FAILURE;
}
if ((flags & _PY_LOCK_PYTHONLOCK) && Py_IsFinalizing()) {
// At this phase of runtime shutdown, only the finalization thread
// can have attached thread state; others hang if they try
// attaching. And since operations on this lock requires attached
// thread state (_PY_LOCK_PYTHONLOCK), the finalization thread is
// running this code, and no other thread can unlock.
// Raise rather than hang. (_PY_LOCK_PYTHONLOCK allows raising
// exceptons.)
PyErr_SetString(PyExc_PythonFinalizationError,
"cannot acquire lock at interpreter finalization");
return PY_LOCK_FAILURE;
}
uint8_t newv = v;
if (!(v & _Py_HAS_PARKED)) {