Asyncio Queue With Workers

Run a pool of workers consuming from an asyncio Queue for producer-consumer patterns.

PythonResilience

Code

pythonsnippet
17 lines
import asyncio
async def worker(queue, processor):
    while True:
        item = await queue.get()
        try:
            await processor(item)
        finally:
            queue.task_done()

async def run_pipeline(items, processor, num_workers=4):
    queue = asyncio.Queue(maxsize=100)
    workers = [asyncio.create_task(worker(queue, processor)) for _ in range(num_workers)]
    for item in items:
        await queue.put(item)
    await queue.join()
    for w in workers:
        w.cancel()

How it works

Asyncio Queue With Workers keeps everything in the functions worker and run_pipeline.

The cycling part of this snippet is while True. Asynchronous boundaries use await, so failures surface as exceptions at the call site rather than being swallowed.

Watch out for

  • Plan for an install step: asyncio is a real dependency, resolved by the package manager.

Putting it to use

The main signature reads def worker(queue, processor)

Import worker from the file and call it — the rest of the code is implementation detail.

Core lines

async def run_pipeline(items, processor, num_workers=4):
    queue = asyncio.Queue(maxsize=100)
    workers = [asyncio.create_task(worker(queue, processor)) for _ in range(num_workers)]
    for item in items:
        await queue.put(item)
    await queue.join()
    for w in workers:
        w.cancel()
async def worker(queue, processor):
    while True:
        item = await queue.get()
        try:
            await processor(item)
        finally:
            queue.task_done()

Interactive Tools for This Topic

FAQ

Which packages must be installed first?
Yes. The imports resolve to `asyncio`, which the package manager must provide.