diff options
author | Victor Stinner <vstinner@python.org> | 2022-09-19 22:13:56 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-09-19 22:13:56 (GMT) |
commit | 04f4977f508583954ad7b9cb09076ee1e57461f8 (patch) | |
tree | 4724eb64e88a0f65d9b978d3a42e5dd1c7cfd560 /Python | |
parent | c10e33ac119d96c4d88d5ae8b59e65a76ae0ad3c (diff) | |
download | cpython-04f4977f508583954ad7b9cb09076ee1e57461f8.zip cpython-04f4977f508583954ad7b9cb09076ee1e57461f8.tar.gz cpython-04f4977f508583954ad7b9cb09076ee1e57461f8.tar.bz2 |
gh-96387: take_gil() resets drop request before exit (#96869)
At Python exit, sometimes a thread holding the GIL can wait forever
for a thread (usually a daemon thread) which requested to drop the
GIL, whereas the thread already exited. To fix the race condition,
the thread which requested the GIL drop now resets its request before
exiting.
take_gil() now calls RESET_GIL_DROP_REQUEST() before
PyThread_exit_thread() if it called SET_GIL_DROP_REQUEST to fix a
race condition with drop_gil().
Issue discovered and analyzed by Mingliang ZHAO.
Diffstat (limited to 'Python')
-rw-r--r-- | Python/ceval_gil.c | 11 |
1 files changed, 11 insertions, 0 deletions
diff --git a/Python/ceval_gil.c b/Python/ceval_gil.c index a679086..fd737b5 100644 --- a/Python/ceval_gil.c +++ b/Python/ceval_gil.c @@ -369,6 +369,7 @@ take_gil(PyThreadState *tstate) goto _ready; } + int drop_requested = 0; while (_Py_atomic_load_relaxed(&gil->locked)) { unsigned long saved_switchnum = gil->switch_number; @@ -384,11 +385,21 @@ take_gil(PyThreadState *tstate) { if (tstate_must_exit(tstate)) { MUTEX_UNLOCK(gil->mutex); + // gh-96387: If the loop requested a drop request in a previous + // iteration, reset the request. Otherwise, drop_gil() can + // block forever waiting for the thread which exited. Drop + // requests made by other threads are also reset: these threads + // may have to request again a drop request (iterate one more + // time). + if (drop_requested) { + RESET_GIL_DROP_REQUEST(interp); + } PyThread_exit_thread(); } assert(is_tstate_valid(tstate)); SET_GIL_DROP_REQUEST(interp); + drop_requested = 1; } } |