Asyncio Queue With Workers
Run a pool of workers consuming from an asyncio Queue for producer-consumer patterns.
Code
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()Report a problem with this exampleOpens a pre-filled issue on GitHub.