asyncio.Queue connects producers and consumers inside an event loop. With maxsize, a fast producer waits when backlog reaches the bound, preventing uncontrolled memory growth.
import asyncio
async def consumidor(fila: asyncio.Queue[int | None]) -> None:
while (item := await fila.get()) is not None:
try:
await asyncio.sleep(0.05)
print(item)
finally:
fila.task_done()
fila.task_done()
async def main() -> None:
fila: asyncio.Queue[int | None] = asyncio.Queue(maxsize=10)
worker = asyncio.create_task(consumidor(fila))
for item in range(5):
await fila.put(item)
await fila.put(None)
await fila.join()
await worker
asyncio.run(main())
Every item retrieved with get() needs task_done(). The sentinel is also an item and must be acknowledged. join() does not stop consumers; it only waits for unfinished work to reach zero.
Practical guidance
Await put() and get() to preserve backpressure. Queue methods do not take a timeout parameter, so wrap the operation with the timeout tool supported by your Python version. Define policies for consumer failures, cancellation, and retryable items in production.
Use asyncio.TaskGroup to supervise multiple consumers. If producers run in threads, choose queue.Queue instead.
The official asyncio.Queue documentation, accessed July 22, 2026, documents the API and its constraints.