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()`.
Run an async entrypoint
Execute a top-level coroutine and manage the event loop automatically.