实现说明
整个示例围绕函数 fetch、main组织。
await 标出每个异步边界——没有悬空的任务。
使用要点
- 预留安装步骤:
asyncio是真实依赖,由包管理器解析。 - 演示输出是带标签的(
results:、peak concurrency:),每个操作都会留下自己的一行标注。 - 值得导入的表面是
fetch;周围的辅助代码对片段是私有的。
常见问题
有第三方依赖吗?
asyncio——运行前用包管理器装上。
主要签名是 def fetch(item: int, sem: asyncio.Semaphore, peak: dict) -> int
核心语句
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}
代码示例
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())