asyncio 是 Python 的框架,用于通过 async/await 实现并发 I/O。它通过事件循环在单个线程上协作运行许多 I/O 操作——对于高并发 I/O 绑定工作(网络调用、Web 服务器)很高效,且没有线程的开销。
定义和运行协程
python
asyncio
():
()
asyncio.sleep()
()
asyncio.run(fetch_data())
async def 函数是一个协程;await 在 I/O 点处暂停它,让事件循环运行其他协程——然后在等待的操作完成时恢复。
# ❌ sequential — total time ≈ 3 seconds
async def slow():
await fetch_data(1) # wait 1s
await fetch_data(2) # then wait 1s
await fetch_data(3) # then wait 1s
# ✅ concurrent — total time ≈ 1 second (all run together)
async def fast():
await asyncio.gather(fetch_data(1), fetch_data(2), fetch_data(3))
asyncio.gather 并发运行协程——当一个等待 I/O 时,其他的继续执行。三个 1 秒的等待重叠为约 1 秒总计。这就是核心价值:在一个线程上叠加许多 I/O 等待。
Threading: OS-managed, preemptive, real threads (GIL-limited for CPU)
asyncio: single thread, COOPERATIVE — coroutines yield at `await` points
→ lighter weight (handle thousands of connections), no thread overhead,
but one CPU-heavy coroutine blocks everything (no preemption)
async def bad():
time.sleep(5) # ❌ BLOCKS the whole event loop (sync sleep)
result = heavy_compute() # ❌ CPU work freezes all coroutines
async def good():
await asyncio.sleep(5) # ✅ non-blocking
# offload CPU work to a thread/process pool
await loop.run_in_executor(None, heavy_compute)
因为它是合作式的且单线程的,任何阻塞/CPU 密集的调用都会冻结所有协程。使用可 await 的异步 API,并将阻塞/CPU 工作卸载到执行器。
✓ High-concurrency I/O: web servers (FastAPI), web scraping, many API/DB calls,
websockets, real-time apps — thousands of concurrent connections efficiently
✗ CPU-bound work — use multiprocessing instead (asyncio doesn't help)
asyncio 是 Python 中高并发 I/O 的现代方法,为 FastAPI 等框架提供支持,并在单个线程上高效处理数千个并发连接——比线程-每-连接方式轻得多。
理解协程、await、用 gather 进行并发执行,尤其是核心规则(不阻塞事件循环;卸载 CPU/阻塞工作)对编写高效的异步 Python 至关重要。
了解什么时候适用(I/O 绑定并发)与什么时候不适用(CPU 绑定 → 多进程)是有效使用它的关键。