Issue #7264: Fix a possible deadlock when deallocating thread-local objects
which are part of a reference cycle.
diff --git a/Lib/_threading_local.py b/Lib/_threading_local.py
index 4eda630..243d84e 100644
--- a/Lib/_threading_local.py
+++ b/Lib/_threading_local.py
@@ -218,10 +218,12 @@
         key = object.__getattribute__(self, '_local__key')
 
         try:
-            threads = list(threading.enumerate())
+            # We use the non-locking API since we might already hold the lock
+            # (__del__ can be called at any point by the cyclic GC).
+            threads = threading._enumerate()
         except:
-            # If enumerate fails, as it seems to do during
-            # shutdown, we'll skip cleanup under the assumption
+            # If enumerating the current threads fails, as it seems to do
+            # during shutdown, we'll skip cleanup under the assumption
             # that there is nothing to clean up.
             return
 
diff --git a/Lib/threading.py b/Lib/threading.py
index cf20152..9ad5122 100644
--- a/Lib/threading.py
+++ b/Lib/threading.py
@@ -810,6 +810,10 @@
 
 active_count = activeCount
 
+def _enumerate():
+    # Same as enumerate(), but without the lock. Internal use only.
+    return _active.values() + _limbo.values()
+
 def enumerate():
     with _active_limbo_lock:
         return _active.values() + _limbo.values()