Python 异步并发:我把 5 个坑踩完了,你照着抄模板就行

0 阅读1分钟

场景:同时请求 200 个接口,串行要 4 分钟,异步 8 秒。但中间你会踩 5 个坑。 本文代码全部可运行,最后给一个可直接复用的并发模板。

先看结论:能用三行说完的,就别写三页

import asyncio

async def main():
    sem = asyncio.Semaphore(20)                 # 坑 1:不限流会打崩对端
    async def task(i):
        async with sem:
            return await fetch(i)
    results = await asyncio.gather(
        *(task(i) for i in range(200)),
        return_exceptions=True,                 # 坑 2:一个失败全盘皆输
    )

这三行背后每一个参数都是被生产环境教育出来的。下面逐个说。


坑 1:gather 一把梭,把对方服务打挂

最常见的写法:

results = await asyncio.gather(*(fetch(u) for u in url_list))

200 个 URL 会在同一个事件循环 tick 里全部发出去。对你的机器没感觉,对目标服务就是一次小型 DDoS —— 轻则 429,重则 IP 被封。

正确做法:Semaphore 显式限流。

import asyncio, aiohttp

async def fetch_all(urls, concurrency=20):
    sem = asyncio.Semaphore(concurrency)
    timeout = aiohttp.ClientTimeout(total=15)

    async with aiohttp.ClientSession(timeout=timeout) as session:
        async def one(url):
            async with sem:
                async with session.get(url) as resp:
                    return resp.status, await resp.text()
        return await asyncio.gather(*(one(u) for u in urls), return_exceptions=True)

并发数怎么定?看对端的限流阈值,不知道就从 10 起,看响应时间和错误率往上调。永远不要不设上限。


坑 2:gather 默认「一错全错」

asyncio.gather 的默认语义是:任意一个协程抛异常,整个 gather 立刻抛出,其余任务的结果全部丢失。

200 个请求里有 3 个 404,你拿不到剩下 197 个成功结果 —— 这在批量任务里是灾难。

# 错误写法:一个 404 就全没了
data = await asyncio.gather(*tasks)

# 正确写法:异常作为结果返回,不中断
data = await asyncio.gather(*tasks, return_exceptions=True)

ok     = [d for d in data if not isinstance(d, Exception)]
failed = [d for d in data if isinstance(d, Exception)]
print(f"成功 {len(ok)} / 失败 {len(failed)}")

代价是异常不会冒泡,你必须自己判 isinstance(x, Exception)。忘了判,后面就会在某个犄角旮旯报 AttributeError: 'Exception' object has no attribute 'json'。


坑 3:在协程里跑了同步阻塞代码

这是异步「看起来没生效」的头号原因。

async def handle():
    requests.get(url)           # 同步库,阻塞整个事件循环!
    time.sleep(1)               # 同上
    open("big.csv").read()      # 大文件 IO 也是

事件循环是单线程的。任何同步阻塞调用都会让所有协程一起卡住,你会观察到「并发 20 个任务,耗时却等于 20 个任务串行」。

三条出路:

情况做法
HTTP 请求换成 aiohttp / httpx.AsyncClient
无法避免的同步库await asyncio.to_thread(func, ...)(3.9+)
CPU 密集计算ProcessPoolExecutor,别放事件循环里
# 同步库的万能包装
result = await asyncio.to_thread(requests.get, url, timeout=10)

to_thread 会把调用丢到线程池执行,事件循环得以继续调度其他协程。注意它有线程池默认上限(min(32, cpu+4)),并发量大时要显式配置。


坑 4:超时只加在 session 上,卡住时无能为力

只设 ClientTimeout(total=15) 不够。真实网络里更常见的是「连接建立了,但对端一直不返回数据」—— 这种情况 total 会等满 15 秒,批量任务里几十个这样的连接就能拖死整个流程。

分层设超时:

timeout = aiohttp.ClientTimeout(
    total=15,          # 最外层兜底
    connect=3,         # 建连:必须短,失败就赶紧换
    sock_read=8,       # 读写:卡住就断
)

再叠加外层的 asyncio.wait_for 做绝对上限:

async def one(url):
    async with sem:
        try:
            return await asyncio.wait_for(fetch(url), timeout=20)
        except asyncio.TimeoutError:
            return {"url": url, "error": "timeout"}

两层配合的意义:内层区分「连不上」和「连上不响应」,外层保证单个任务不会无限期占着信号量。


坑 5:Windows 上 RuntimeError: Event loop is closed

本地 macOS 跑得好好的,CI 的 Windows 机器一跑就炸。

原因:Python 3.8+ 在 Windows 上默认用 ProactorEventLoop,配合 aiohttp 的某些版本,在循环关闭后仍有未回收的连接,就会抛这个错。

两个修法,任选其一:

# 方案 A:切回 Selector 事件循环(最省事,3.8-3.11 有效)
import asyncio, sys
if sys.platform == "win32":
    asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())

# 方案 B:确保 Session 在循环关闭前被 await 关闭(根治)
# 别把 ClientSession 存成全局变量,一定放在 async with 里

另外 Python 3.12 起 get_event_loop() 的隐式创建行为被弃用,用 asyncio.run() 包住入口就不会有这个问题。


附:可直接复用的并发模板

把上面五点合成一个函数,改 worker 就能用:

import asyncio
from typing import Any, Awaitable, Callable, Iterable

async def run_concurrently(
    items: Iterable[Any],
    worker: Callable[[Any], Awaitable[Any]],
    concurrency: int = 20,
    timeout: float = 20.0,
) -> tuple[list[Any], list[tuple[Any, BaseException]]]:
    """并发执行,返回 (成功结果列表, [(输入, 异常), ...])"""
    sem = asyncio.Semaphore(concurrency)

    async def guard(item):
        async with sem:
            try:
                return item, await asyncio.wait_for(worker(item), timeout), None
            except BaseException as e:      # 注意:含 CancelledError
                return item, None, e

    out = await asyncio.gather(*(guard(i) for i in items))
    ok  = [r for _, r, e in out if e is None]
    bad = [(i, e) for i, r, e in out if e is not None]
    return ok, bad


# 用法
async def main():
    ok, bad = await run_concurrently(urls, fetch, concurrency=20)
    print(f"成功 {len(ok)},失败 {len(bad)}")
    for item, err in bad[:5]:
        print(f"  {item} -> {type(err).__name__}: {err}")

if __name__ == "__main__":
    asyncio.run(main())

这个模板的价值在于:失败是数据,不是异常。批量任务里你总能拿到完整账本 —— 谁成功了、谁失败了、为什么失败,而不是在主流程里包一堆 try/except。


一句话总结

异步写错的典型症状是「以为并发了,其实串行」或者「并发了,但把对面打挂了」。对照检查:

  • 有没有 Semaphore 限流
  • gather 有没有 return_exceptions=True
  • 协程里有没有同步阻塞调用
  • 超时是分了连接/读写两层,还是一层兜底
  • 入口是不是 asyncio.run()

五条都对上,异步才算真的跑起来了。


文中的 run_concurrently 模板我整理成了带注释和测试用例的版本,另外配了一份「异步批量任务」检查清单,需要的话评论区说一声。