Python 3.4+Async programmingterm
asyncio.Queue
queue
A queue for passing data between coroutines. put/get are awaited. Not thread-safe: use queue.Queue to pass data between threads.
Syntax
q = asyncio.Queue(maxsize=0)
await q.put(item)
item = await q.get()
The hard part is stopping the consumer: await q.get() on an empty queue waits forever, and looping on q.empty() is a race — the producer may simply not have put the item yet. The usual exits are a sentinel value (say None) or marking work with task_done() and waiting on q.join(). A maxsize above zero makes put itself a suspension point, giving you backpressure so a fast producer cannot outrun a slow consumer.
Examples
import asyncio
async def producer(q):
for i in range(3):
await q.put(i)
async def consumer(q):
while not q.empty():
v = await q.get()
print(v) # → 0 / 1 / 2
async def main():
q = asyncio.Queue()
await producer(q)
await consumer(q)
asyncio.run(main())
See also
Open in the full glossarydocs.python.orgReport an inaccuracy