Skip to content

gh-136003: Execute pre-finalization callbacks in a loop #136004

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 23 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
354e6b5
Execute early finalization handlers in a loop
ZeroIntensity Jun 26, 2025
3090524
Store Py_MAX result in a variable.
ZeroIntensity Jun 26, 2025
43038b8
Add a test in test_atexit.
ZeroIntensity Jun 26, 2025
8d4151c
Deal with it in Py_EndInterpreter() as well.
ZeroIntensity Jun 26, 2025
add4d33
Add a blurb entry.
ZeroIntensity Jun 26, 2025
3edc3a8
Check the return code in the test.
ZeroIntensity Jun 26, 2025
ec57918
Add a test for pending calls.
ZeroIntensity Jun 26, 2025
970153b
Fix tests on Windows.
ZeroIntensity Jun 26, 2025
cfd62b8
Use os.linesep.
ZeroIntensity Jul 3, 2025
859070f
Use an RW lock instead of a counter.
ZeroIntensity Jul 3, 2025
37098a0
Merge branch 'main' of https://github.com/python/cpython into fix-cir…
ZeroIntensity Jul 3, 2025
8a1aa13
Remove more counters.
ZeroIntensity Jul 3, 2025
cbcd552
Remove old artifacts (again).
ZeroIntensity Jul 9, 2025
54613a1
Final time removing artifacts.
ZeroIntensity Jul 9, 2025
9ccdb5f
(I lied)
ZeroIntensity Jul 9, 2025
9cd75b7
Atomically check if there are threads, atexit callbacks, or pending c…
ZeroIntensity Jul 9, 2025
1360059
Remove stray newline change.
ZeroIntensity Jul 9, 2025
475538a
Add a test for atexit with subinterpreters.
ZeroIntensity Jul 10, 2025
a794188
Check for os.pipe() in the test.
ZeroIntensity Jul 10, 2025
2dda7a4
Rely on stop-the-world and the GIL instead of a dedicated RW mutex.
ZeroIntensity Jul 10, 2025
f1460af
Serialize pending calls via the ceval mutex.
ZeroIntensity Jul 10, 2025
1e1301d
Only check for non-daemon threads at finalization.
ZeroIntensity Jul 10, 2025
51a20d4
Fix assertion failures on the GILful build.
ZeroIntensity Jul 24, 2025
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
Prev Previous commit
Next Next commit
Rely on stop-the-world and the GIL instead of a dedicated RW mutex.
This solution is much simpler, but will perform a little bit worse.
Instead of using a dedicated lock on the interpreter state, we can
simply use stop-the-world (and the GIL on the default build) to ensure that
no other threads can create pre-finalization callbacks concurrently.
  • Loading branch information
ZeroIntensity committed Jul 10, 2025
commit 2dda7a4b4ea4989d0790cf4fb5f28e15fdc8743c
4 changes: 0 additions & 4 deletions Include/internal/pycore_interp_structs.h
Original file line number Diff line number Diff line change
Expand Up @@ -971,10 +971,6 @@ struct _is {
# endif
#endif

/* The "pre-finalization" lock, which protects against things like starting
* threads. The exclusive writer is only used when the interpreter finalizes. */
_PyRWMutex prefini_mutex;

/* the initial PyInterpreterState.threads.head */
_PyThreadStateImpl _initial_thread;
// _initial_thread should be the last field of PyInterpreterState.
Expand Down
22 changes: 8 additions & 14 deletions Modules/_threadmodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -176,13 +176,11 @@ ThreadHandle_get_os_handle(ThreadHandle *handle, PyThread_handle_t *os_handle)
}

static void
add_to_shutdown_handles(thread_module_state *state, ThreadHandle *handle, PyInterpreterState *interp)
add_to_shutdown_handles(thread_module_state *state, ThreadHandle *handle)
{
_PyRWMutex_RLock(&interp->prefini_mutex);
HEAD_LOCK(&_PyRuntime);
llist_insert_tail(&state->shutdown_handles, &handle->shutdown_node);
HEAD_UNLOCK(&_PyRuntime);
_PyRWMutex_RUnlock(&interp->prefini_mutex);
}

static void
Expand All @@ -197,16 +195,13 @@ clear_shutdown_handles(thread_module_state *state)
}

static void
remove_from_shutdown_handles(ThreadHandle *handle, PyInterpreterState *interp)
remove_from_shutdown_handles(ThreadHandle *handle)
{
assert(interp != NULL);
_PyRWMutex_RLock(&interp->prefini_mutex);
HEAD_LOCK(&_PyRuntime);
if (handle->shutdown_node.next != NULL) {
llist_remove(&handle->shutdown_node);
}
HEAD_UNLOCK(&_PyRuntime);
_PyRWMutex_RUnlock(&interp->prefini_mutex);
}

static ThreadHandle *
Expand Down Expand Up @@ -314,7 +309,7 @@ _PyThread_AfterFork(struct _pythread_runtime_state *state)
handle->mutex = (PyMutex){_Py_UNLOCKED};
_PyEvent_Notify(&handle->thread_is_exiting);
llist_remove(node);
remove_from_shutdown_handles(handle, _PyInterpreterState_GET());
remove_from_shutdown_handles(handle);
}
}

Expand Down Expand Up @@ -347,7 +342,6 @@ thread_run(void *boot_raw)
{
struct bootstate *boot = (struct bootstate *) boot_raw;
PyThreadState *tstate = boot->tstate;
PyInterpreterState *interp = tstate->interp;

// Wait until the handle is marked as running
PyEvent_Wait(&boot->handle_ready);
Expand All @@ -374,7 +368,7 @@ thread_run(void *boot_raw)

_PyThreadState_Bind(tstate);
PyEval_AcquireThread(tstate);
_Py_atomic_add_ssize(&interp->threads.count, 1);
_Py_atomic_add_ssize(&tstate->interp->threads.count, 1);

PyObject *res = PyObject_Call(boot->func, boot->args, boot->kwargs);
if (res == NULL) {
Expand All @@ -392,13 +386,13 @@ thread_run(void *boot_raw)

thread_bootstate_free(boot, 1);

_Py_atomic_add_ssize(&interp->threads.count, -1);
_Py_atomic_add_ssize(&tstate->interp->threads.count, -1);
PyThreadState_Clear(tstate);
_PyThreadState_DeleteCurrent(tstate);

exit:
// Don't need to wait for this thread anymore
remove_from_shutdown_handles(handle, interp);
remove_from_shutdown_handles(handle);

_PyEvent_Notify(&handle->thread_is_exiting);
ThreadHandle_decref(handle);
Expand Down Expand Up @@ -1877,12 +1871,12 @@ do_start_new_thread(thread_module_state *state, PyObject *func, PyObject *args,
// Add the handle before starting the thread to avoid adding a handle
// to a thread that has already finished (i.e. if the thread finishes
// before the call to `ThreadHandle_start()` below returns).
add_to_shutdown_handles(state, handle, interp);
add_to_shutdown_handles(state, handle);
}

if (ThreadHandle_start(handle, func, args, kwargs) < 0) {
if (!daemon) {
remove_from_shutdown_handles(handle, interp);
remove_from_shutdown_handles(handle);
}
return -1;
}
Expand Down
8 changes: 1 addition & 7 deletions Modules/atexitmodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -196,15 +196,9 @@ atexit_register(PyObject *module, PyObject *args, PyObject *kwargs)
return NULL;
}

PyInterpreterState *interp = _PyInterpreterState_GET();
assert(interp != NULL);
struct atexit_state *state = get_atexit_state();
_PyRWMutex_RLock(&interp->prefini_mutex);
// atexit callbacks go in a LIFO order
int res = PyList_Insert(state->callbacks, 0, callback);
_PyRWMutex_RUnlock(&interp->prefini_mutex);

if (res < 0)
if (PyList_Insert(state->callbacks, 0, callback) < 0)
{
Py_DECREF(callback);
return NULL;
Expand Down
13 changes: 1 addition & 12 deletions Python/ceval_gil.c
Original file line number Diff line number Diff line change
Expand Up @@ -785,10 +785,8 @@ _PyEval_AddPendingCall(PyInterpreterState *interp,
}

PyMutex_Lock(&pending->mutex);
_PyRWMutex_RLock(&interp->prefini_mutex);
_Py_add_pending_call_result result =
_push_pending_call(pending, func, arg, flags);
_PyRWMutex_RUnlock(&interp->prefini_mutex);
PyMutex_Unlock(&pending->mutex);

if (main_only) {
Expand Down Expand Up @@ -919,7 +917,7 @@ clear_pending_handling_thread(struct _pending_calls *pending)
}

static int
make_pending_calls_lock_held(PyThreadState *tstate)
make_pending_calls(PyThreadState *tstate)
{
PyInterpreterState *interp = tstate->interp;
struct _pending_calls *pending = &interp->ceval.pending;
Expand Down Expand Up @@ -977,15 +975,6 @@ make_pending_calls_lock_held(PyThreadState *tstate)
return 0;
}

static int
make_pending_calls(PyThreadState *tstate)
{
_PyRWMutex_RLock(&tstate->interp->prefini_mutex);
int res = make_pending_calls_lock_held(tstate);
_PyRWMutex_RUnlock(&tstate->interp->prefini_mutex);
return res;
}


void
_Py_set_eval_breaker_bit_all(PyInterpreterState *interp, uintptr_t bit)
Expand Down
12 changes: 9 additions & 3 deletions Python/pylifecycle.c
Original file line number Diff line number Diff line change
Expand Up @@ -2036,6 +2036,8 @@ make_pre_finalization_calls(PyThreadState *tstate)
* could start a thread or vice versa. To ensure that we properly clean
* call everything, we run these in a loop until none of them run anything. */
for (;;) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would it make sense to add an arbitrary limit to detect infinite loop? For example, log an error after 16 attemps.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well, it would prevent deadlocks in rare cases, but it would cause crashes in other equally rare cases. Maybe it would be better to emit a fatal error when there are too many iterations?

assert(!interp->runtime->stoptheworld.world_stopped);

// Wrap up existing "threading"-module-created, non-daemon threads.
wait_for_thread_shutdown(tstate);

Expand All @@ -2054,15 +2056,18 @@ make_pre_finalization_calls(PyThreadState *tstate)

_PyAtExit_Call(tstate->interp);

_PyRWMutex_Lock(&tstate->interp->prefini_mutex);
// XXX Why does _PyThreadState_DeleteList() rely on all interpreters
// being stopped?
_PyEval_StopTheWorldAll(interp->runtime);
int should_continue = (interp_has_threads(interp)
|| interp_has_atexit_callbacks(interp)
|| interp_has_pending_calls(interp));
_PyRWMutex_Unlock(&tstate->interp->prefini_mutex);
if (!should_continue) {
break;
}
_PyEval_StartTheWorldAll(interp->runtime);
}
assert(interp->runtime->stoptheworld.world_stopped);
}

static int
Expand Down Expand Up @@ -2099,7 +2104,7 @@ _Py_Finalize(_PyRuntimeState *runtime)
#endif

/* Ensure that remaining threads are detached */
_PyEval_StopTheWorldAll(runtime);
assert(tstate->interp->runtime->stoptheworld.world_stopped);

/* Remaining daemon threads will be trapped in PyThread_hang_thread
when they attempt to take the GIL (ex: PyEval_RestoreThread()). */
Expand Down Expand Up @@ -2490,6 +2495,7 @@ Py_EndInterpreter(PyThreadState *tstate)
/* Remaining daemon threads will automatically exit
when they attempt to take the GIL (ex: PyEval_RestoreThread()). */
_PyInterpreterState_SetFinalizing(interp, tstate);
_PyEval_StartTheWorldAll(interp->runtime);

// XXX Call something like _PyImport_Disable() here?

Expand Down
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy