为什么要异步
异步编程在处理 I/O 密集型任务时能让程序不阻塞。Python 从 3.5 开始引入 async/await 语法,asyncio 库提供了事件循环和任务管理能力。
协程:可以暂停的函数
用 async def 定义,用 await 等待另一个协程。一个简单的例子:
import asyncio
async def hello():
print('Hello, World!')
await asyncio.sleep(1)
print('Hello again!')
asyncio.run(hello())
asyncio.sleep(1) 模拟 I/O 操作,这时候事件循环可以去做别的事。
并发运行多个协程
当你有多个协程时,可以用 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())
三个 count 协程几乎是同时开始的,总耗时大约 1 秒。
任务调度:更细粒度的控制
asyncio.create_task 把协程包装成任务,让你可以单独取消或等待:
import asyncio
async def hello():
print('Hello, World!')
await asyncio.sleep(1)
print('Hello again!')
async ():
task1 = asyncio.create_task(hello())
task2 = asyncio.create_task(hello())
task1
task2
asyncio.run(main())


