示例工程 20-taskgroup-cancellation-contextvars
20-taskgroup-cancellation-contextvars/03-semaphore-throttle/semaphore_throttle.py
"""演示 Semaphore 限制并发度。"""
from __future__ import annotations
import asyncio
async def task(
index: int,
semaphore: asyncio.Semaphore,
active: list[int],
peak: list[int],
) -> int:
async with semaphore:
active.append(index)
peak[0] = max(peak[0], len(active))
await asyncio.sleep(0.01)
active.remove(index)
return index
async def run(count: int = 20, limit: int = 5) -> tuple[list[int], int]:
semaphore = asyncio.Semaphore(limit)
active: list[int] = []
peak = [0]
results = await asyncio.gather(
*(task(index, semaphore, active, peak) for index in range(count))
)
return list(results), peak[0]
async def main() -> None:
results, peak = await run()
print(f"completed: {len(results)}")
print(f"peak: {peak}")
if __name__ == "__main__":
asyncio.run(main())