Asyncio Queue Worker Pool
Fan out jobs to a bounded asyncio queue, run a fixed worker pool, and shut down cleanly with sentinel values and task_done.
Code
import asyncio
from dataclasses import dataclass
@dataclass(frozen=True)
class Job:
identifier: int
payload: str
async def worker(
name: str,
queue: "asyncio.Queue[Job | None]",
results: list[tuple[str, int]],
) -> None:
while True:
job = await queue.get()
try:
if job is None:
return
await asyncio.sleep(0.01)
results.append((name, job.identifier))
finally:
queue.task_done()
async def run_jobs(jobs: list[Job], workers: int = 3) -> list[tuple[str, int]]:
if workers < 1:
raise ValueError("workers must be positive")
queue: asyncio.Queue[Job | None] = asyncio.Queue(maxsize=workers * 2)
results: list[tuple[str, int]] = []
tasks = [
asyncio.create_task(worker(f"worker-{index}", queue, results))
for index in range(workers)
]
for job in jobs:
await queue.put(job)
for _ in tasks:
await queue.put(None)
await queue.join()
await asyncio.gather(*tasks)
return results
def main() -> None:
jobs = [Job(index, f"payload-{index}") for index in range(8)]
results = asyncio.run(run_jobs(jobs))
print(f"processed {len(results)} jobs")
for name, identifier in sorted(results, key=lambda row: row[1]):
print(name, "->", identifier)
assert sorted(identifier for _, identifier in results) == list(range(8))
if __name__ == "__main__":
main()How it works
One way to read it: the class Job and the functions worker, run_jobs and main, doing all the work.
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. From asyncio it pulls dataclass — the imports name exactly which library surface the snippet touches. ValueError is the guard’s signal — thrown at the branch, before any partial work happens.
The input results is mutated in place — callers that need the original must pass a copy.
What to watch for
- Dependency check:
asyncio— not built-in, must be present in the project. - The guard
workers < 1short-circuits the flow with an earlyraisewhen its condition holds. resultsis mutated in place — the value you pass will not be the same afterward.
Putting it to use
The primary signature is def worker( name: str, queue: "asyncio.Queue[Job | None]", results: list[tuple[str, int]], ) -> None
Running the file prints labeled results such as processed — each operation’s effect is visible in the output.
The sequence run_jobs lives in main; running the file triggers it.
Core lines
for name, identifier in sorted(results, key=lambda row: row[1]):
print(name, "->", identifier)
async def worker(
name: str,
queue: "asyncio.Queue[Job | None]",
results: list[tuple[str, int]],
) -> None:
if job is None:
return
Interactive Tools for This Topic
FAQ
- Does `worker` modify its input?
- Yes — `results` is mutated in place. Pass a copy if the caller needs the original preserved.
- How does the snippet fail?
- The code throws `ValueError` — the guard `workers < 1` rejects bad states before the main logic runs. Handle it at the call site or let it propagate deliberately.
- Do I need to install anything before running this?
- Yes: `asyncio` must be present in the project or the import fails at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.