Back
+30 XP
Concept

Async Barrier Synchronization Primitive

When N distributed tasks or simulation nodes must initialize independently before launching an action together, an async barrier synchronizes them. Every arriving coroutine blocks until the target party threshold is met, releasing all participants simultaneously.

python
import asyncio

class AsyncBarrier:
    def __init__(self, parties: int):
        self.parties = parties
        self.count = 0
        self.cond = asyncio.Condition()

# Async Barrier Synchronization Primitive Imagine launching a high-throughput load test with 50 worker coroutines. If worker 1 starts hitting the server while worker 50 is still establishing TLS handshakes, your test results are ruined. 🛑⏱️ An **Async Barrier** forces all $N$ participating coroutines to rendezvous at a synchronization point. Each worker reaches `barrier.wait()` and pauses until the last expected party arrives. Once full, the barrier unlocks and lets everyone charge forward together. ```python import asyncio class AsyncBarrier: def __init__(self, parties: int): self.parties = parties self.count = 0 self.cond = asyncio.Condition() ``` ## Pop Quiz What differentiates a cyclic barrier from a one-time countdown latch? - [ ] A barrier resets its party counter and generation automatically, allowing repeated reuse. - [ ] A barrier uses OS kernel semaphores while countdown latches operate purely in userspace. - [ ] A barrier can only release one single coroutine while permanently terminating the others. - [ ] A countdown latch requires exactly two parties and does not support asyncio. ## Real-World Challenge Construct an `AsyncBarrier(parties: int)` primitive. The `await wait()` method blocks until all `parties` have arrived, returns a unique zero-indexed arrival position to each caller, and automatically resets so the barrier can be reused across rounds. <details> <summary>Solution</summary> ```python import asyncio class AsyncBarrier: def __init__(self, parties: int): if parties < 1: raise ValueError("parties must be at least 1") self.parties = parties self.count = 0 self.generation = 0 self.cond = asyncio.Condition() async def wait(self) -> int: async with self.cond: gen = self.generation index = self.count self.count += 1 if self.count == self.parties: self.generation += 1 self.count = 0 self.cond.notify_all() return index while gen == self.generation: await self.cond.wait() return index # Verification async def run_test(): barrier = AsyncBarrier(3) arrivals = [] async def worker(w_id: int): idx = await barrier.wait() arrivals.append((w_id, idx)) await asyncio.gather(worker(10), worker(20), worker(30)) assert len(arrivals) == 3 indices = sorted([pos for _, pos in arrivals]) assert indices == [0, 1, 2] asyncio.run(run_test()) ``` </details>