Python 异步编程与协程实战指南
为什么需要异步?
传统的同步编程中,程序必须等待一个操作(比如网络请求或文件读写)完成后才能继续执行下一个。这在 I/O 密集型场景下非常浪费资源。异步编程允许程序在等待 I/O 完成时切换到其他任务,从而在不增加线程开销的前提下大幅提升并发能力。
它特别适合以下场景:
- 网络通信:HTTP 请求、WebSocket 等。
- 文件操作:大文件的读写。
- 数据库查询:减少等待时间。
核心概念:协程与事件循环
什么是协程
协程(Coroutine)是一种轻量级的用户态线程。在 Python 中,使用 async def 关键字定义协程函数。与普通函数不同,协程可以被暂停(await)并在稍后恢复执行。
import asyncio
async def hello():
print('Hello, World!')
await asyncio.sleep(1) # 模拟耗时操作,不阻塞主线程
print('Hello again!')
# 运行协程
asyncio.run(hello())
任务调度与并发
我们可以创建多个任务并让它们并发执行。asyncio.gather() 是常用的工具,它能等待一组协程全部完成。
import asyncio
async def count():
print('Counting...')
await asyncio.sleep(1)
print('Counted!')
async def main():
# 同时启动三个计数任务
await asyncio.gather(count(), count(), count())
asyncio.run(main())


