Skip to content

Commit d1942cd

Browse files
vstinnerlisroach
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.
1 parent 76adaab commit d1942cd

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
@@ -761,6 +761,14 @@ def test_shutdown_locks(self):
761761
# Daemon threads must never add it to _shutdown_locks.
762762
self.assertNotIn(tstate_lock, threading._shutdown_locks)
763763

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

765773
class ThreadJoinOnShutdown(BaseTestCase):
766774

Lib/threading.py

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

809+
def __del__(self):
810+
if not self._initialized:
811+
return
812+
lock = self._tstate_lock
813+
if lock is not None and not self.daemon:
814+
# ensure that self._tstate_lock is not in _shutdown_locks
815+
# if join() was not called explicitly
816+
with _shutdown_locks_lock:
817+
_shutdown_locks.discard(lock)
818+
809819
def _reset_internal_locks(self, is_alive):
810820
# private! Called by _after_fork() to reset our internal locks as
811821
# 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)