Python asyncio 并发实战:从 gather 到 TaskGroup
I/O 密集型任务(网络请求、数据库查询)是 asyncio 的主场。本文用“批量请求 1000 个 URL”这个场景,一步步写出一个生产可用的并发版本。
#最朴素的写法
python
import asyncio
import httpx
async def fetch(client: httpx.AsyncClient, url: str) -> int:
resp = await client.get(url)
return resp.status_code
async def main(urls: list[str]):
async with httpx.AsyncClient() as client:
results = await asyncio.gather(*(fetch(client, u) for u in urls))
print(results)问题:1000 个请求同时发出,可能被目标服务器限流,也可能耗尽本地文件描述符。
#用 Semaphore 限制并发数
python
async def fetch(client, url, sem: asyncio.Semaphore):
async with sem: # 同一时刻最多 N 个协程进入
resp = await client.get(url, timeout=10)
return resp.status_code
async def main(urls):
sem = asyncio.Semaphore(20)
async with httpx.AsyncClient() as client:
return await asyncio.gather(
*(fetch(client, u, sem) for u in urls),
return_exceptions=True, # 单个失败不影响整体
)return_exceptions=True 很关键:否则任意一个请求抛异常,gather 会立即把异常抛给你,而其他任务仍在后台运行。
#整体超时
python
try:
async with asyncio.timeout(30): # Python 3.11+
results = await main(urls)
except TimeoutError:
print("30 秒内没有全部完成")#TaskGroup:结构化并发
Python 3.11 引入的 TaskGroup 保证:退出 async with 块时,组内所有任务都已结束。任一任务失败,其余任务会被自动取消。
python
async def main(urls):
sem = asyncio.Semaphore(20)
async with httpx.AsyncClient() as client:
async with asyncio.TaskGroup() as tg:
tasks = [tg.create_task(fetch(client, u, sem)) for u in urls]
return [t.result() for t in tasks]#什么时候用哪个?
| 场景 | 推荐 |
|---|---|
| 允许部分失败,收集所有结果 | gather(..., return_exceptions=True) |
| 要么全成功,要么快速失败 | TaskGroup |
| 边完成边处理 | asyncio.as_completed |
#常见坑
- 在协程里调用阻塞函数:
time.sleep、requests.get会卡住整个事件循环,应改用await asyncio.sleep或asyncio.to_thread(blocking_fn)。 - 忘记 await:
fetch(url)只创建了协程对象,并没有执行。 - CPU 密集型任务:asyncio 帮不上忙,请用
ProcessPoolExecutor。