Python 异步编程:asyncio 深入理解与实战指南

By | 2026年10月24日

为什么需要 asyncio?

在 I/O 密集型应用中,同步阻塞模型会导致大量时间浪费在等待网络响应、磁盘读写上。Python 的 asyncio 提供了一种基于事件循环的并发模型,允许单线程内并发执行多个任务,特别适合高并发的网络服务、爬虫和微服务。

但很多开发者对 asyncio 的理解停留在 async/await 语法层面,遇到性能问题或诡异 bug 时无从下手。本文将从事件循环底层出发,结合实战代码,带你真正掌握 asyncio。

环境准备

确保 Python 版本 ≥ 3.8(推荐 3.10+),并安装 aiohttp 用于网络请求示例:


pip install aiohttp

第一步:理解协程与事件循环

1.1 协程的本质

协程(coroutine)是可以通过 async def 定义的函数,调用时不会立即执行,而是返回一个协程对象。它需要被事件循环调度才会运行。


import asyncio

async def hello():
    print("Hello")
    await asyncio.sleep(1)
    print("World")

# 直接调用不会执行
coro = hello()
print(type(coro))  # <class 'coroutine'>

# 通过事件循环运行
asyncio.run(hello())

asyncio.run() 是 Python 3.7+ 推荐的入口,它自动创建事件循环、运行协程并清理资源。

1.2 事件循环的工作原理

事件循环是 asyncio 的核心,它维护一个任务队列,不断轮询 I/O 事件和定时器,当某个任务就绪时恢复其执行。你可以把它想象成一个调度器,在单线程内实现协作式多任务。


import asyncio

async def task(name, delay):
    print(f"Task {name} started")
    await asyncio.sleep(delay)
    print(f"Task {name} finished")

async def main():
    # 并发运行两个任务
    await asyncio.gather(
        task("A", 2),
        task("B", 1)
    )

asyncio.run(main())

输出顺序:Task A started → Task B started → Task B finished → Task A finished。这证明两个任务在等待时交替执行。

第二步:任务、Future 与并发控制

2.1 Task:协程的调度单元

asyncio.create_task() 将协程包装为 Task,立即加入事件循环调度。与 await 直接调用不同,Task 是并发执行的。


async def main():
    task1 = asyncio.create_task(task("A", 2))
    task2 = asyncio.create_task(task("B", 1))
    
    # 等待所有任务完成
    await task1
    await task2

2.2 Future:低层级的占位对象

Future 表示一个异步操作的最终结果,通常由底层回调设置。日常开发中较少直接使用,但理解它有助于阅读库源码。


async def set_future(fut):
    await asyncio.sleep(1)
    fut.set_result("done")

async def main():
    loop = asyncio.get_running_loop()
    fut = loop.create_future()
    asyncio.create_task(set_future(fut))
    result = await fut
    print(result)  # done

2.3 并发限制:Semaphore

无限制地创建任务可能导致资源耗尽。使用 asyncio.Semaphore 控制并发数:


import asyncio
import aiohttp

async def fetch(url, session, sem):
    async with sem:
        async with session.get(url) as response:
            return await response.text()

async def main():
    urls = [f"https://httpbin.org/delay/1?i={i}" for i in range(10)]
    sem = asyncio.Semaphore(3)  # 最大并发 3
    async with aiohttp.ClientSession() as session:
        tasks = [fetch(url, session, sem) for url in urls]
        results = await asyncio.gather(*tasks)
        print(f"Fetched {len(results)} pages")

asyncio.run(main())

第三步:实战——异步爬虫与超时控制

3.1 带超时的请求

网络请求必须设置超时,避免任务永久挂起。asyncio.wait_for 可以包装任意协程:


async def fetch_with_timeout(url, session, timeout=5):
    try:
        async with session.get(url, timeout=timeout) as response:
            return await response.text()
    except asyncio.TimeoutError:
        print(f"Timeout: {url}")
        return None

async def main():
    async with aiohttp.ClientSession() as session:
        result = await fetch_with_timeout("https://httpbin.org/delay/10", session, timeout=3)
        print(result is None)  # True

3.2 任务取消与清理

当某个任务失败或超时时,及时取消其他任务可以释放资源:


async def worker(name):
    try:
        await asyncio.sleep(10)
    except asyncio.CancelledError:
        print(f"Worker {name} cancelled")
        raise

async def main():
    tasks = [asyncio.create_task(worker(i)) for i in range(3)]
    await asyncio.sleep(1)
    for t in tasks:
        t.cancel()
    await asyncio.gather(*tasks, return_exceptions=True)

asyncio.run(main())

第四步:常见陷阱与最佳实践

💡 陷阱1:在协程中调用阻塞函数

同步阻塞函数(如 time.sleep、requests.get)会阻塞整个事件循环,导致所有任务卡住。务必使用异步替代品,或通过 loop.runinexecutor 放到线程池执行。


import time
import asyncio
from concurrent.futures import ThreadPoolExecutor

def blocking_io():
    time.sleep(2)
    return "done"

async def main():
    loop = asyncio.get_running_loop()
    with ThreadPoolExecutor() as pool:
        result = await loop.run_in_executor(pool, blocking_io)
        print(result)

💡 陷阱2:忘记 await

调用协程函数但忘记 await 会导致协程从未执行,且不会报错(除非启用警告)。开启 asyncio 调试模式可检测:


import asyncio
import warnings

async def foo():
    pass

async def main():
    foo()  # 忘记 await

# 启用调试模式
asyncio.run(main(), debug=True)

会输出警告:coroutine 'foo' was never awaited。

💡 陷阱3:异常处理

asyncio.gather 默认遇到第一个异常就抛出,其他任务继续运行但结果被丢弃。使用 return_exceptions=True 收集所有结果:


async def fail():
    raise ValueError("oops")

async def main():
    results = await asyncio.gather(fail(), asyncio.sleep(1, result="ok"), return_exceptions=True)
    print(results)  # [ValueError('oops'), 'ok']

最佳实践清单

  • 使用 asyncio.run() 作为程序入口,避免手动管理事件循环。
  • 为所有网络请求设置超时(aiohttp.ClientTimeout)。
  • 使用 asyncio.Semaphore 限制并发,防止资源耗尽。
  • 在协程中避免任何同步阻塞调用,必要时使用 runinexecutor。
  • 使用 asyncio.create_task() 时保留引用,防止任务被垃圾回收。

总结

asyncio 的强大源于事件循环的协作式调度,但正确使用需要理解协程、任务和 Future 的关系。通过本文的示例,你应该掌握了并发控制、超时处理和异常管理的关键技巧。下一步可以探索 asyncio.Queue 实现生产者-消费者模式,或结合 uvloop 提升性能。

延伸阅读:

  • 官方文档 asyncio — Asynchronous I/O
  • uvloop:基于 libuv 的高性能事件循环
  • anyio:兼容 asyncio 和 trio 的异步抽象层