第三十章:异步编程

完成本章学习后,你将能够:

  • 理解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())
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/chapter30.txt
  • 最后更改: 2026/04/09 14:39
  • 张叶安