Skip to content

Commit 9ad58ac

Browse files
authored
bpo-19466: Py_Finalize() clears daemon threads earlier (GH-18848)
Clear the frames of daemon threads earlier during the Python shutdown to call objects destructors. So "unclosed file" resource warnings are now emitted for daemon threads in a more reliable way. Cleanup _PyThreadState_DeleteExcept() code: rename "garbage" to "list".
1 parent 8e9c47a commit 9ad58ac

File tree

4 files changed

+70
-7
lines changed

4 files changed

+70
-7
lines changed

Lib/test/test_threading.py

+45
Original file line numberDiff line numberDiff line change
@@ -759,6 +759,51 @@ def test_shutdown_locks(self):
759759
# Daemon threads must never add it to _shutdown_locks.
760760
self.assertNotIn(tstate_lock, threading._shutdown_locks)
761761

762+
def test_locals_at_exit(self):
763+
# bpo-19466: thread locals must not be deleted before destructors
764+
# are called
765+
rc, out, err = assert_python_ok("-c", """if 1:
766+
import threading
767+
768+
class Atexit:
769+
def __del__(self):
770+
print("thread_dict.atexit = %r" % thread_dict.atexit)
771+
772+
thread_dict = threading.local()
773+
thread_dict.atexit = "value"
774+
775+
atexit = Atexit()
776+
""")
777+
self.assertEqual(out.rstrip(), b"thread_dict.atexit = 'value'")
778+
779+
def test_warnings_at_exit(self):
780+
# bpo-19466: try to call most destructors at Python shutdown before
781+
# destroying Python thread states
782+
filename = __file__
783+
rc, out, err = assert_python_ok("-Wd", "-c", """if 1:
784+
import time
785+
import threading
786+
from test import support
787+
788+
def open_sleep():
789+
# a warning will be emitted when the open file will be
790+
# destroyed (without being explicitly closed) while the daemon
791+
# thread is destroyed
792+
fileobj = open(%a, 'rb')
793+
start_event.set()
794+
time.sleep(support.LONG_TIMEOUT)
795+
796+
start_event = threading.Event()
797+
798+
thread = threading.Thread(target=open_sleep, daemon=True)
799+
thread.start()
800+
801+
# wait until the thread started
802+
start_event.wait()
803+
""" % filename)
804+
self.assertRegex(err.rstrip(),
805+
b"^sys:1: ResourceWarning: unclosed file ")
806+
762807

763808
class ThreadJoinOnShutdown(BaseTestCase):
764809

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Clear the frames of daemon threads earlier during the Python shutdown to
2+
call objects destructors. So "unclosed file" resource warnings are now
3+
emitted for daemon threads in a more reliable way.

Python/pylifecycle.c

+10
Original file line numberDiff line numberDiff line change
@@ -1373,6 +1373,16 @@ Py_FinalizeEx(void)
13731373
runtime->initialized = 0;
13741374
runtime->core_initialized = 0;
13751375

1376+
/* Destroy the state of all threads of the interpreter, except of the
1377+
current thread. In practice, only daemon threads should still be alive,
1378+
except if wait_for_thread_shutdown() has been cancelled by CTRL+C.
1379+
Clear frames of other threads to call objects destructors. Destructors
1380+
will be called in the current Python thread. Since
1381+
_PyRuntimeState_SetFinalizing() has been called, no other Python thread
1382+
can take the GIL at this point: if they try, they will exit
1383+
immediately. */
1384+
_PyThreadState_DeleteExcept(runtime, tstate);
1385+
13761386
/* Flush sys.stdout and sys.stderr */
13771387
if (flush_std_files() < 0) {
13781388
status = -1;

Python/pystate.c

+12-7
Original file line numberDiff line numberDiff line change
@@ -895,25 +895,30 @@ void
895895
_PyThreadState_DeleteExcept(_PyRuntimeState *runtime, PyThreadState *tstate)
896896
{
897897
PyInterpreterState *interp = tstate->interp;
898-
PyThreadState *p, *next, *garbage;
898+
899899
HEAD_LOCK(runtime);
900900
/* Remove all thread states, except tstate, from the linked list of
901901
thread states. This will allow calling PyThreadState_Clear()
902902
without holding the lock. */
903-
garbage = interp->tstate_head;
904-
if (garbage == tstate)
905-
garbage = tstate->next;
906-
if (tstate->prev)
903+
PyThreadState *list = interp->tstate_head;
904+
if (list == tstate) {
905+
list = tstate->next;
906+
}
907+
if (tstate->prev) {
907908
tstate->prev->next = tstate->next;
908-
if (tstate->next)
909+
}
910+
if (tstate->next) {
909911
tstate->next->prev = tstate->prev;
912+
}
910913
tstate->prev = tstate->next = NULL;
911914
interp->tstate_head = tstate;
912915
HEAD_UNLOCK(runtime);
916+
913917
/* Clear and deallocate all stale thread states. Even if this
914918
executes Python code, we should be safe since it executes
915919
in the current thread, not one of the stale threads. */
916-
for (p = garbage; p; p = next) {
920+
PyThreadState *p, *next;
921+
for (p = list; p; p = next) {
917922
next = p->next;
918923
PyThreadState_Clear(p);
919924
PyMem_RawFree(p);

0 commit comments

Comments
 (0)