bpo-37788: Fix a reference leak if a thread is not joined (GH-15228)
authorVictor Stinner <vstinner@redhat.com>
Mon, 19 Aug 2019 22:37:17 +0000 (23:37 +0100)
committerGitHub <noreply@github.com>
Mon, 19 Aug 2019 22:37:17 +0000 (23:37 +0100)
Add threading.Thread.__del__() method to ensure that the thread state
lock is removed from the _shutdown_locks list when a thread
completes.

Lib/test/test_threading.py
Lib/threading.py
Misc/NEWS.d/next/Library/2019-08-12-17-21-10.bpo-37788.F0tR05.rst [new file with mode: 0644]

index 7c16974c1630a7eaf275b2b0b07887640b4d53a2..5e90627822f9f880c13d755a1ad17c422b2e455d 100644 (file)
@@ -761,6 +761,14 @@ class ThreadTests(BaseTestCase):
                 # Daemon threads must never add it to _shutdown_locks.
                 self.assertNotIn(tstate_lock, threading._shutdown_locks)
 
+    def test_leak_without_join(self):
+        # bpo-37788: Test that a thread which is not joined explicitly
+        # does not leak. Test written for reference leak checks.
+        def noop(): pass
+        with support.wait_threads_exit():
+            threading.Thread(target=noop).start()
+            # Thread.join() is not called
+
 
 class ThreadJoinOnShutdown(BaseTestCase):
 
index 32a3d7c3033621f0604cfea91726e3d3a44f1748..67e1c4facfee282631b39815ee8f84464a14f0c1 100644 (file)
@@ -806,6 +806,16 @@ class Thread:
         # For debugging and _after_fork()
         _dangling.add(self)
 
+    def __del__(self):
+        if not self._initialized:
+            return
+        lock = self._tstate_lock
+        if lock is not None and not self.daemon:
+            # ensure that self._tstate_lock is not in _shutdown_locks
+            # if join() was not called explicitly
+            with _shutdown_locks_lock:
+                _shutdown_locks.discard(lock)
+
     def _reset_internal_locks(self, is_alive):
         # private!  Called by _after_fork() to reset our internal locks as
         # they may be in an invalid state leading to a deadlock or crash.
diff --git a/Misc/NEWS.d/next/Library/2019-08-12-17-21-10.bpo-37788.F0tR05.rst b/Misc/NEWS.d/next/Library/2019-08-12-17-21-10.bpo-37788.F0tR05.rst
new file mode 100644 (file)
index 0000000..d9b1e82
--- /dev/null
@@ -0,0 +1 @@
+Fix a reference leak if a thread is not joined.