====== 第三十章:异步编程 ====== ===== 本章目标 ===== 完成本章学习后,你将能够: * 理解asyncio编程模型 * 使用async/await * 创建和运行协程 * 处理异步I/O ===== 基础概念 ===== import asyncio async def hello(): print("Hello") await asyncio.sleep(1) print("World") # 运行 asyncio.run(hello()) ===== 创建任务 ===== 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()) ===== 并发执行 ===== 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()) ===== 异步I/O ===== 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()) ===== 本章练习 ===== 1. 实现异步HTTP客户端 2. 实现异步爬虫 3. 实现协程调度器 下一章:[[python_course:chapter31|第三十一章:并发模式]]