[New-bugs-announce] [issue45278] RuntimeError on race on weakset concurrent iteration
report at bugs.python.org
Fri Sep 24 07:03:08 EDT 2021
New submission from Ben <benjsimner at gmail.com>:
This is a very subtle race
WeakSet uses _weakrefset.py's _IterationGuard structure to protect against the case where the elements the WeakSet refers to get cleaned up while a thread is iterating over the WeakSet.
It defers the actual removal of any elements which get gc'd during iteration until the end of the iteration.
the WeakSet keeps track of all the iterators, and waits until there are no more threads iterating over the set before it does the removal: https://github.com/python/cpython/blob/main/Lib/_weakrefset.py#L30
However there is a race, if another thread begins iterating after the `if s:` check but before the _commit_removals call has ended, that iteration can get a RuntimeError.
attached is an example script that can generate such RuntimeError's,
although the race window here is very small and so to observe yourself you may have to tweak the magic constants around.
As far as I'm aware nobody has reported seeing this bug happen in production, but some libraries (e.g. asyncio) do currently rely on concurrently iterating a weakset, so it's not implausible.
title: RuntimeError on race on weakset concurrent iteration
Added file: https://bugs.python.org/file50302/weakset_concurrent_iter_runtimeerror.py
Python tracker <report at bugs.python.org>
More information about the New-bugs-announce