Python Glossary Русский

Python 3.4+Async programmingterm

asyncio.Condition

synchronization

A condition variable: a task waits under a lock until some condition holds, while another task changes the state and wakes waiters with notify() or notify_all().

Syntax

cond = asyncio.Condition()
async with cond: await cond.wait_for(predicate)

Both wait() and notify() are allowed only inside async with cond, otherwise RuntimeError. A woken task does not know the condition holds — the state may have changed again — so instead of if plus wait() you write a loop or simply await cond.wait_for(predicate). If you only wait for 'it happened', asyncio.Event is simpler; for passing data, asyncio.Queue.

Examples

import asyncio
items = []
async def consumer(cond):
    async with cond:
        await cond.wait_for(lambda: len(items) >= 2)
        print('получено', items)  # → получено [1, 2]
async def main():
    cond = asyncio.Condition()
    task = asyncio.create_task(consumer(cond))
    for x in (1, 2):
        await asyncio.sleep(0.01)
        async with cond:
            items.append(x)
            cond.notify_all()
    await task
asyncio.run(main())
import asyncio
async def main():
    cond = asyncio.Condition()
    try:
        cond.notify()
    except RuntimeError as e:
        print(e)  # → cannot notify on un-acquired lock
    await asyncio.sleep(0.01)
asyncio.run(main())

See also

Open in the full glossarydocs.python.orgReport an inaccuracy