← 中文资源

简体中文版本

用信号量限制异步并发

运行大量异步协程并用信号量限制并发度,避免无界并发导致的待处理任务洪流。

阅读英文原文

实现说明

逻辑集中在函数 gather_limited、guarded、fetch、main里。 await 标出每个异步边界——没有悬空的任务。asyncio 提供的就是 Awaitable、List、TypeVar——API 接触面仅此而已。ValueError 是守卫的信号——在分支处抛出,任何半成品工作之前。

使用要点

  • 依赖检查:asyncio——不是内建的,项目里必须有。
  • 守卫 limit <= 0 满足时靠提前的 raise 短路流程。
  • 调用方只需要 gather_limited——其余都是内部实现。

常见问题

这段代码会校验输入吗?

校验先行——ValueError 标记失败(位于 limit <= 0),不会先做一半再失败。

它需要从包仓库拿什么?

这些是真实的依赖:asyncio。缺了就加载不起来。

主要签名是 def gather_limited( tasks: List[Awaitable[T]], limit: int ) -> List[T]

核心语句

async def main() -> None:
    results = await gather_limited([fetch(i) for i in range(20)], 5)
    print(len(results))
async def guarded(task: Awaitable[T]) -> T:
    async with semaphore:
        return await task
async def fetch(i: int) -> str:
    await asyncio.sleep(0.01)
    return f"item-{i}"

代码示例

import asyncio
from typing import Awaitable, List, TypeVar

T = TypeVar("T")


async def gather_limited(
    tasks: List[Awaitable[T]], limit: int
) -> List[T]:
    if limit <= 0:
        raise ValueError("limit must be positive")
    semaphore = asyncio.Semaphore(limit)

    async def guarded(task: Awaitable[T]) -> T:
        async with semaphore:
            return await task

    return await asyncio.gather(*(guarded(t) for t in tasks))


async def fetch(i: int) -> str:
    await asyncio.sleep(0.01)
    return f"item-{i}"


async def main() -> None:
    results = await gather_limited([fetch(i) for i in range(20)], 5)
    print(len(results))