显示页面讨论过去修订反向链接回到顶部 本页面只读。您可以查看源文件,但不能更改它。如果您觉得这是系统错误,请联系管理员。 ====== 第三十章:异步编程 ====== ===== 本章目标 ===== 完成本章学习后,你将能够: * 理解asyncio编程模型 * 使用async/await * 创建和运行协程 * 处理异步I/O ===== 基础概念 ===== <code python> import asyncio async def hello(): print("Hello") await asyncio.sleep(1) print("World") # 运行 asyncio.run(hello()) </code> ===== 创建任务 ===== <code python> async def task(name, delay): print(f"Task {name} started") await asyncio.sleep(delay) print(f"Task {name} finished") async def main(): # 创建任务 t1 = asyncio.create_task(task("A", 2)) t2 = asyncio.create_task(task("B", 1)) # 等待完成 await t1 await t2 asyncio.run(main()) </code> ===== 并发执行 ===== <code python> async def main(): # gather并发执行 results = await asyncio.gather( task("A", 2), task("B", 1), task("C", 3) ) # 等待多个,带超时 done, pending = await asyncio.wait( [task("A", 2), task("B", 1)], timeout=1.5 ) asyncio.run(main()) </code> ===== 异步I/O ===== <code python> import aiohttp async def fetch_url(url): async with aiohttp.ClientSession() as session: async with session.get(url) as response: return await response.text() async def main(): urls = ['https://api.github.com'] * 10 tasks = [fetch_url(url) for url in urls] results = await asyncio.gather(*tasks) asyncio.run(main()) </code> ===== 本章练习 ===== 1. 实现异步HTTP客户端 2. 实现异步爬虫 3. 实现协程调度器 下一章:[[python_course:chapter31|第三十一章:并发模式]] 登录 Detach Close 该主题尚不存在 您访问的页面并不存在。如果允许,您可以使用创建该页面按钮来创建它。 python/chapter30.txt 最后更改: 2026/04/09 14:39由 张叶安 登录