diff --git a/Lib/weakref.py b/Lib/weakref.py index 994ea8aa37..53edbc0cae 100644 --- a/Lib/weakref.py +++ b/Lib/weakref.py @@ -23,6 +23,7 @@ from _weakrefset import WeakSet, _IterationGuard import _collections_abc # Import after _weakref to avoid circular import. import sys +import time import itertools ProxyTypes = (ProxyType, CallableProxyType) @@ -103,6 +104,7 @@ class WeakValueDictionary(_collections_abc.MutableMapping): # way in). def __init__(self, other=(), /, **kw): + should_sleep = True def remove(wr, selfref=ref(self), _atomic_removal=_remove_dead_weakref): self = selfref() if self is not None: @@ -111,6 +113,10 @@ class WeakValueDictionary(_collections_abc.MutableMapping): else: # Atomic removal is necessary since this function # can be called asynchronously by the GC + nonlocal should_sleep + if should_sleep: + time.sleep(0.02) + should_sleep = False _atomic_removal(self.data, wr.key) self._remove = remove # A list of keys to be removed @@ -185,6 +191,7 @@ class WeakValueDictionary(_collections_abc.MutableMapping): if self._pending_removals: self._commit_removals() new = self.__class__() + time.sleep(0.01) with _IterationGuard(self): for key, wr in self.data.items(): o = wr()