It does make sense to have a barrier synchronization primitive for asyncio.
The idea is to make a coroutine block until at least X coroutines are waiting to enter the barrier.
This is very useful, if certain actions need to be synchronized.
Recently, I had to implement a barier myself for our use case. See code below:
It is simple to implement, but I too would like to have one for asyncio, in order to be consistent with the concurrency primitives we have for threading.
Jonathan
class Barier:
"""
Make a coroutine block until there are at least X waiters.
Similar to the threading Barier objects but for asyncio:
https://docs.python.org/3/library/threading.html#barrier-objects """
def __init__(self, parties: int) -> None:
self.parties = parties
self._waiting: int
self._event = asyncio.Event()
def add_one(self) -> None:
self._waiting += 1
if self._waiting == self.parties:
self._event.set()
async def wait(self, worker: "Worker") -> None:
"""
Wait until all we have at least `parties` waiters.
"""
self.add_one()
await self._event.wait()