asyncio-pool

0.6.0 · active · verified Thu Apr 16

asyncio-pool is a Python library that provides a pool for asyncio coroutines, offering a familiar interface similar to `multiprocessing.Pool`. It ensures that a controlled number of coroutines are active concurrently, managing task scheduling and results. The current version is 0.6.0, released in May 2022, with a stalled release cadence but remains functional.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to create an `AioPool`, use its `map` method to process an iterable of items concurrently, and individually `spawn` coroutines. The `async with` statement ensures the pool is properly shut down and all tasks are awaited.

import asyncio
from asyncio_pool import AioPool

async def worker(n: int) -> int:
    """A dummy async worker that simulates some work."""
    print(f"Worker {n}: Starting...")
    await asyncio.sleep(1 / (n + 1)) # Simulate work, avoid division by zero
    print(f"Worker {n}: Done.")
    return n * 2

async def main():
    pool_size = 5
    todo_items = range(10)

    print(f"Creating a pool with size {pool_size}")
    async with AioPool(size=pool_size) as pool:
        print("Mapping tasks to the pool...")
        # Map worker function over todo_items, collect results
        results = await pool.map(worker, todo_items)
        print(f"All tasks completed. Results: {results}")

        # Example of spawning individual tasks
        print("Spawning individual tasks...")
        futures = []
        for i in range(3):
            futures.append(pool.spawn(worker(i + 10)))
        # Await all spawned tasks to complete explicitly if not using map/itermap
        final_results = await asyncio.gather(*futures)
        print(f"Individual tasks completed. Results: {final_results}")

if __name__ == "__main__":
    asyncio.run(main())

view raw JSON →