Z
ZHANK
异步编程

async/await 基础

协程概念、async def/await、asyncio.run、可等待对象

async/await 基础

async def 定义协程,await 等待结果——用同步的写法写异步代码,核心是事件循环

学完本章你将: 掌握协程概念、async/await、asyncio.run、可等待对象。


第一个异步程序

python
import asyncio

async def say_hello():
    print("Hello...")
    await asyncio.sleep(1)  # 模拟 IO 等待——不阻塞
    print("...World!")

async def main():
    await say_hello()

asyncio.run(main())

并发执行多个协程

python
async def fetch(url):
    print(f"开始请求 {url}")
    await asyncio.sleep(1)  # 模拟网络 IO
    return f"{url} 的数据"

async def main():
    # 并发执行——总共只等 1 秒(不是 3 秒)
    results = await asyncio.gather(
        fetch("http://a.com"),
        fetch("http://b.com"),
        fetch("http://c.com"),
    )
    print(results)

asyncio.run(main())

协程 vs 普通函数

python
# 普通函数
def compute():
    return 42

# 协程函数
async def async_compute():
    await asyncio.sleep(0.1)
    return 42

# 协程函数调用返回协程对象,不立即执行
coro = async_compute()  # 返回 coroutine 对象
result = asyncio.run(coro)  # 用事件循环执行

可等待对象

python
# 三种可 await 的对象:
# 1. 协程对象:async def 的返回值
# 2. Task:asyncio.create_task() 创建
# 3. Future:低级对象(一般用 Task 替代)

async def main():
    # 协程
    await async_compute()

    # Task——立即调度,不等待
    task = asyncio.create_task(async_compute())
    result = await task  # 在这里等待结果