官方资料与延伸阅读
本教程主要参考下面资料。内容以 Python 3.14.5 稳定文档为主,也补充了 Python 3.15 开发文档里已经写明的变化方向。
Python 官方文档
| 资料 | 用途 |
|---|---|
| asyncio 总览 | 确认 asyncio 适合做什么,以及哪些 API 更常用 |
| A Conceptual Overview of asyncio | 分清 event loop、coroutine、Task、Future、await 各自负责什么 |
| Runners | 理解 asyncio.run()、Runner、loop 生命周期和 Python 3.14 变化 |
| Coroutines and Tasks | 查 Task、TaskGroup、gather、timeout、shield 和取消规则 |
| Event Loop | 查 loop 低层 API、callback、timer、Future/Task 创建、I/O 方法 |
| Streams | 查 StreamReader、StreamWriter、drain()、TCP server/client |
| Queues | 查 Queue、PriorityQueue、LifoQueue、Python 3.13 的 shutdown |
| Synchronization Primitives | 查 Lock、Event、Condition、Semaphore、Barrier |
| Developing with asyncio | 查 debug 模式、线程边界、阻塞调用、未等待 coroutine 等排错内容 |
| Transports and Protocols | 理解 Streams 下面那套 callback 风格的网络接口 |
| High-level API Index | 快速查高层 API |
| Low-level API Index | 快速查低层 API |
CPython 源码
| 资料 | 用途 |
|---|---|
| CPython Lib/asyncio | 查看 asyncio 标准库源码目录 |
| runners.py | asyncio.run() 和 Runner |
| base_events.py | BaseEventLoop 和 _run_once |
| tasks.py | Task、gather、sleep |
| futures.py | Future |
| queues.py | Queue |
| streams.py | Streams |
| taskgroups.py | TaskGroup |
版本提示
- 本教程 Demo 按 Python 3.12+ 来写。
TaskGroup和asyncio.timeout()从 Python 3.11 开始可用。- Python 3.13 为
asyncio.Queue增加了 shutdown 相关功能。 - Python 3.14 文档记录了
asyncio.run()和Runner.run()可以接受任意 awaitable。 - Python 3.15 开发文档提示 asyncio policy system 已弃用并计划在 Python 3.16 移除。教程中因此倾向讲
get_running_loop()和显式loop_factory的方向。
继续怎么读
别一口气读完整源码。按任务走:
- 读
asyncio.run()到run_until_complete()。 - 读
asyncio.sleep()如何使用 timer Future。 - 读
Task如何让 coroutine 继续执行。 - 读
Queue.get()和Queue.put()如何用 Future 唤醒等待者。 - 读 Streams 如何把 Protocol callback 转成 awaitable reader/writer。
- 再看
TaskGroup如何处理取消和异常聚合。