Skip to content

Instantly share code, notes, and snippets.

@twisteroidambassador
Created April 11, 2017 10:00
Show Gist options
  • Save twisteroidambassador/dc7fb769854e99fb94b98ec67c24ffff to your computer and use it in GitHub Desktop.
Save twisteroidambassador/dc7fb769854e99fb94b98ec67c24ffff to your computer and use it in GitHub Desktop.
An (partial) asyncio version of threads.Barrier. There's only wait(), no reset() or abort() or concept of being broken, and like all other asyncio->threading analogues, no timeouts.
import asyncio
class Barrier():
"""asyncio version of threading.Barrier (partial).
Implements wait() only, without support for timeouts."""
def __init__(self, parties, loop=None):
if loop is None:
self._loop = asyncio.get_event_loop()
else:
self._loop = loop
self.parties = parties
self.n_waiting = 0
self._master_fut = asyncio.Future(loop=self._loop)
@asyncio.coroutine
def wait(self):
n = self.n_waiting
self.n_waiting += 1
if self.n_waiting > self.parties:
raise RuntimeError('Barrier already passed')
if self.n_waiting == self.parties:
self._master_fut.set_result(None)
yield from self._master_fut
return n
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment