Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
Ignore non-daemon threads when KeyboardInterrupt is sent during final…
…ization.
  • Loading branch information
ZeroIntensity committed Sep 18, 2025
commit 8f9e6759203f4a32b8a813e697d9d06c9707dfd7
4 changes: 1 addition & 3 deletions Modules/_threadmodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -2429,10 +2429,8 @@ thread_shutdown(PyObject *self, PyObject *args)
// Wait for the thread to finish. If we're interrupted, such
// as by a ctrl-c we print the error and exit early.
if (ThreadHandle_join(handle, -1) < 0) {
PyErr_FormatUnraisable("Exception ignored while joining a thread "
"in _thread._shutdown()");
ThreadHandle_decref(handle);
Py_RETURN_NONE;
return NULL;
}

ThreadHandle_decref(handle);
Expand Down
25 changes: 23 additions & 2 deletions Python/pylifecycle.c
Original file line number Diff line number Diff line change
Expand Up @@ -3548,6 +3548,27 @@ Py_ExitStatusException(PyStatus status)
}


static void
handle_thread_shutdown_exception(PyThreadState *tstate)
{
assert(tstate != NULL);
assert(_PyErr_Occurred(tstate));
PyInterpreterState *interp = tstate->interp;
assert(interp->threads.head != NULL);
_PyEval_StopTheWorld(interp);

// We don't have to worry about locking this because the
// world is stopped.
_Py_FOR_EACH_TSTATE_UNLOCKED(interp, tstate) {
if (tstate->_whence == _PyThreadState_WHENCE_THREADING) {
tstate->_whence = _PyThreadState_WHENCE_THREADING_DAEMON;
}
}

_PyEval_StartTheWorld(interp);
PyErr_FormatUnraisable("Exception ignored on threading shutdown");
}

/* Wait until threading._shutdown completes, provided
the threading module was imported in the first place.
The shutdown routine will wait until all non-daemon
Expand All @@ -3559,14 +3580,14 @@ wait_for_thread_shutdown(PyThreadState *tstate)
PyObject *threading = PyImport_GetModule(&_Py_ID(threading));
if (threading == NULL) {
if (_PyErr_Occurred(tstate)) {
PyErr_FormatUnraisable("Exception ignored on threading shutdown");
handle_thread_shutdown_exception(tstate);
}
/* else: threading not imported */
return;
}
result = PyObject_CallMethodNoArgs(threading, &_Py_ID(_shutdown));
if (result == NULL) {
PyErr_FormatUnraisable("Exception ignored on threading shutdown");
handle_thread_shutdown_exception(tstate);
}
else {
Py_DECREF(result);
Expand Down