Python Glossary Русский

Python 3.11+Async programmingterm

asyncio.Barrier

synchronization

A barrier: tasks wait in await barrier.wait() until the given number of parties has arrived, and only then do they all continue together. Added in Python 3.11.

Syntax

barrier = asyncio.Barrier(parties); index = await barrier.wait()

The barrier is reusable: once a batch passes, it waits for parties tasks again. With fewer tasks than parties the waiters hang forever, so wrap wait() in asyncio.timeout(). Cancelling a waiting task does not break the barrier — that task just leaves and the waiting count drops; barrier.abort() breaks it, and then every waiter gets asyncio.BrokenBarrierError. wait() returns an index from 0 to parties-1 — handy to let exactly one task do a shared step.

Examples

import asyncio
async def worker(name, barrier):
    await asyncio.sleep(0.01)
    index = await barrier.wait()
    if index == 0:
        print('все на месте')  # → все на месте
async def main():
    barrier = asyncio.Barrier(3)
    await asyncio.gather(*(worker(n, barrier) for n in 'abc'))
    print(barrier.parties, barrier.n_waiting)  # → 3 0
asyncio.run(main())

See also

Open in the full glossarydocs.python.orgReport an inaccuracy