8000 bpo-37788: Fix a reference leak if a thread is not joined (GH-15228) · miss-islington/cpython@2d61971 · GitHub
[go: up one dir, main page]

Skip to content

Commit 2d61971

Browse files
vstinnermiss-islington
authored andcommitted
bpo-37788: Fix a reference leak if a thread is not joined (pythonGH-15228)
Add threading.Thread.__del__() method to ensure that the thread state lock is removed from the _shutdown_locks list when a thread completes. (cherry picked from commit d3dcc92) Co-authored-by: Victor Stinner <vstinner@redhat.com>
1 parent 0fcdd8d commit 2d61971

File tree

3 files changed

+19
-0
lines changed

3 files changed

+19
-0
lines changed

Lib/test/test_threading.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -757,6 +757,14 @@ def test_shutdown_locks(self):
757757
# Daemon threads must never add it to _shutdown_locks.
758758
self.assertNotIn(tstate_lock, threading._shutdown_locks)
759759

760+
def test_leak_without_join(self):
761+
# bpo-37788: Test that a thread which is not joined explicitly
762+
# does not leak. Test written for reference leak checks.
763+
def noop(): pass
764+
with support.wait_threads_exit():
765+
threading.Thread(target=noop).start()
766+
# Thread.join() is not called
767+
760768

761769
class ThreadJoinOnShutdown(BaseTestCase):
762770

Lib/threading.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -805,6 +805,16 @@ class is implemented.
805805
# For debugging and _after_fork()
806806
_dangling.add(self)
807807

808+
def __del__(self):
809+
if not self._initialized:
810+
return
811+
lock = self._tstate_lock
812+
if lock is not None and not self.daemon:
813+
# ensure that self._tstate_lock is not in _shutdown_locks
814+
# if join() was not called explicitly
815+
with _shutdown_locks_lock:
816+
_shutdown_locks.discard(lock)
817+
808818
def _reset_internal_locks(self, is_alive):
809819
# private! Called by _after_fork() to reset our internal locks as
810820
# they may be in an invalid state leading to a deadlock or crash.
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix a reference leak if a thread is not joined.

0 commit comments

Comments
 (0)
0