同步 vs 异步:一个例子

假设要请求 3 个 API,每个耗时 1 秒:

# 同步:总耗时 3 秒
import requests
import time

start = time.time()
for url in urls:
    requests.get(url)  # 等 1 秒
print(f"同步耗时: {time.time()-start:.1f}s")  # 3.0s

# 异步:总耗时 1 秒
import asyncio
import aiohttp

async def fetch(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as resp:
            return await resp.text()

async def main():
    tasks = [fetch(url) for url in urls]
    await asyncio.gather(*tasks)

start = time.time()
asyncio.run(main())
print(f"异步耗时: {time.time()-start:.1f}s")  # 1.0s

核心概念

概念说明
协程(Coroutine)用 async def 定义的函数,调用时不立即执行,返回协程对象
事件循环(Event Loop)负责调度所有协程,在等待时切换执行其他协程
await等待一个协程完成,同时不阻塞事件循环
Task协程被包装成 Task 后加入事件循环并发执行
gather并发执行多个协程,等待全部完成

为什么异步能提速

关键在于等待。同步代码在等待网络响应时,CPU 是空转的。异步代码在等待时,事件循环会去执行其他协程。

这不是多线程,也不是多进程——整个程序在一个线程里跑。只是在 I/O 等待的间隙,切换到其他协程。所以:

常用模式

并发执行多个任务

async def main():
    # 方式一:gather
    results = await asyncio.gather(
        fetch(url1), fetch(url2), fetch(url3),
        return_exceptions=True  # 某个失败不影响其他
    )

    # 方式二:as_completed(先完成先处理)
    tasks = [asyncio.create_task(fetch(u)) for u in urls]
    for coro in asyncio.as_completed(tasks):
        result = await coro
        print("完成一个")

超时控制

async def fetch_with_timeout(url):
    try:
        async with aiohttp.ClientSession() as session:
            async with session.get(url) as resp:
                return await asyncio.wait_for(resp.text(), timeout=5)
    except asyncio.TimeoutError:
        return "超时"

信号量限制并发数

sem = asyncio.Semaphore(5)  # 最多同时5个请求

async def fetch(url):
    async with sem:  # 信号量保护
        async with aiohttp.ClientSession() as session:
            async with session.get(url) as resp:
                return await resp.text()

# 即使有1000个URL,同时只有5个在请求
tasks = [fetch(u) for u in urls]
await asyncio.gather(*tasks)

常见坑

  1. 在协程里调用同步阻塞函数:time.sleep(1) 会阻塞整个事件循环!要用 await asyncio.sleep(1)
  2. 忘记 await:fetch(url) 创建了协程但没执行,Python 会警告。必须 await fetch(url) 或 asyncio.create_task(fetch(url))
  3. 同步库不能直接用:requests、redis-py(同步版)会阻塞事件循环。要用 aiohttp、aioredis 等异步版本。
  4. 数据库连接池:异步数据库驱动需要连接池,不能每个请求新建连接。

异步 Web 框架对比

框架特点适合场景
FastAPI类型提示、自动文档、高性能API 服务(首选)
aiohttp灵活、底层爬虫、微服务
Starlette轻量 ASGI 框架FastAPI 的底层
Tornado老牌、WebSocket 支持好长连接服务