Asyncio Gather With Concurrency Limits

Bound concurrent coroutines with a semaphore inside gather so a large batch does not open every connection at once.

PythonResilience

Code

pythonsnippet
24 lines
import asyncio


async def fetch(item: int, sem: asyncio.Semaphore, peak: dict) -> int:
    async with sem:  # 同时持有的协程数不超过 sem 容量
        peak['now'] += 1
        peak['max'] = max(peak['max'], peak['now'])
        try:
            await asyncio.sleep(0.01)  # 模拟 IO
            return item * 2
        finally:
            peak['now'] -= 1


async def main() -> None:
    sem = asyncio.Semaphore(3)
    peak = {'now': 0, 'max': 0}

    results = await asyncio.gather(*(fetch(i, sem, peak) for i in range(12)))
    print('results:', results[:5], '... total', len(results))
    print('peak concurrency:', peak['max'])  # 3


asyncio.run(main())

How it works

Asyncio Gather With Concurrency Limits keeps everything in the functions fetch and main.

Asynchronous boundaries use await, so failures surface as exceptions at the call site rather than being swallowed.

What to watch for

  • Dependency check: asyncio — not built-in, must be present in the project.

Using it

The primary signature is def fetch(item: int, sem: asyncio.Semaphore, peak: dict) -> int

Expect labeled output — results:, peak concurrency: — when the file runs.

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

Key statements

async def main() -> None:
    sem = asyncio.Semaphore(3)
    peak = {'now': 0, 'max': 0}
    results = await asyncio.gather(*(fetch(i, sem, peak) for i in range(12)))
    print('results:', results[:5], '... total', len(results))
    print('peak concurrency:', peak['max'])  # 3
async with sem:  # 同时持有的协程数不超过 sem 容量
peak['now'] += 1
peak['max'] = max(peak['max'], peak['now'])
try:
await asyncio.sleep(0.01)  # 模拟 IO
return item * 2
finally:
peak['now'] -= 1
async def main() -> None:
sem = asyncio.Semaphore(3)
peak = {'now': 0, 'max': 0}

Interactive Tools for This Topic

FAQ

Are there third-party dependencies?
`asyncio` — install it with the package manager before running.