完成本章学习后,你将能够:
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())
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. 实现协程调度器
下一章:第三十一章:并发模式