Python asyncio Cheat Sheet/Use an asyncio.Queue

Exchange work between producers and consumers.

Section: Queues and Producer/Consumer Patterns

Use an asyncio.Queue

python
python
import asyncio

async def producer(queue):
    for item in [1, 2, 3]:
        await queue.put(item)
    await queue.put(None)

async def consumer(queue):
    while True:
        item = await queue.get()
        if item is None:
            queue.task_done()
            break
        print(item)
        queue.task_done()

async def main():
    queue = asyncio.Queue()
    await asyncio.gather(producer(queue), consumer(queue))
    await queue.join()

asyncio.run(main())
Explanation

Queues are designed for async code and are not thread-safe.

Learn the surrounding workflow

Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.

Related commands

Same sheet · prioritizing Queues and Producer/Consumer Patterns
Add a timeout to queue operations
Wrap queue operations with `wait_for()`.
OpenIn sheetpythonsame section
Use a PriorityQueue
Process lower-number priorities first.
OpenIn sheetpythonsame section
Run an async entrypoint
Execute a top-level coroutine and manage the event loop automatically.
Create a background task
Schedule a coroutine to run concurrently.
Cancel a task
Request cancellation and await the task to observe it.
Protect shared state with a Lock
Prevent overlapping access to a critical section.