黄同学的后端和 Agent 笔记开通
Hello 后端

动手做:一起查 10 个商品

黄同学约 4 分钟读完免费

要查 10 个商品的价格和库存,算出这批货一共值多少钱。查一次价格要等 1 秒,查一次库存也要等 1 秒,现在的代码一个一个查,要 20 秒。你要把它改成一起查、同时最多 5 个,再修好一个会卡住事件循环的调用。做完以后,同样的结果 4 秒就出来。

要先学过:

这一页只用 Python 自带的库,不用装别的。

步骤

  1. 在 ~/hb-python 里建一个目录 async-lab,进去:

    bash
    cd ~/hb-python
    mkdir async-lab
    cd async-lab
  2. 新建 fake_api.py,照抄,后面不用改。它是一个假的商品接口:get_price 是异步的;get_stock_blocking 假装是一个只有同步版本的库,里面用的是 time.sleep。它还偷偷记下两件事:同时最多有几个商品在查(max_concurrent),get_stock_blocking 有几次是在事件循环的线程里被调用的(blocking_on_loop)。

    python
    # 假的商品接口:查一次价格、查一次库存,都要等 1 秒。
    import asyncio
    import threading
    import time
    
    _lock = threading.Lock()
    _checking: set[int] = set()  # 正在查的商品
    max_concurrent = 0
    blocking_on_loop = 0
    
    
    async def get_price(pid: int) -> int:
        """查价格(分)。异步的,等的时候会让出。"""
        global max_concurrent
        with _lock:
            _checking.add(pid)
            max_concurrent = max(max_concurrent, len(_checking))
        await asyncio.sleep(1)
        return 1000 + pid * 100
    
    
    def get_stock_blocking(pid: int) -> int:
        """查库存。假装是一个只有同步版本的库:time.sleep 不会让出。"""
        global blocking_on_loop
        try:
            asyncio.get_running_loop()  # 拿得到,说明是在事件循环的线程里被调用的
            with _lock:
                blocking_on_loop += 1
        except RuntimeError:
            pass  # 在别的线程里,没有正在运行的事件循环,正好
        time.sleep(1)
        with _lock:
            _checking.discard(pid)
        return pid * 2
    
    
    def report() -> None:
        print(f"max_concurrent={max_concurrent}")
        print(f"blocking_on_loop={blocking_on_loop}")

    get_stock_blocking 会被几个线程同时调用,所以改那几个计数时加了一把锁(线程、进程和 GIL最后一节)。

  3. 新建 main.py,照抄。这是现在的样子:一个一个 await,库存直接调了同步函数。

    python
    import asyncio
    import time
    
    from fake_api import get_price, get_stock_blocking, report
    
    
    async def main() -> None:
        start = time.perf_counter()
        total = 0
        for pid in range(1, 11):
            price = await get_price(pid)
            stock = get_stock_blocking(pid)
            total += price * stock
        print(f"total={total}")
        report()
        print(f"elapsed={time.perf_counter() - start:.1f}")
    
    
    asyncio.run(main())
  4. 运行,耐心等 20 秒:

    bash
    uv run main.py
    text
    total=187000
    max_concurrent=1
    blocking_on_loop=10
    elapsed=20.1

    total 是这批货值多少钱(分),改完以后它不能变。max_concurrent=1:同一时刻只有 1 个商品在查。blocking_on_loop=10:10 次库存查询都是在事件循环的线程里调的,每次把它卡住 1 秒。

  5. 改成一起查。写一个 async def check_one(pid: int) -> int,先查价格、再查库存,返回 price * stock;用 TaskGroup 把 10 个商品一起交给事件循环;再用一个 asyncio.Semaphore(5) 包住 check_one 里的两次查询,同时最多 5 个商品在查。库存先照旧直接调 get_stock_blocking(pid)。

    答案
    python
    import asyncio
    import time
    
    from fake_api import get_price, get_stock_blocking, report
    
    sem = asyncio.Semaphore(5)
    
    
    async def check_one(pid: int) -> int:
        async with sem:
            price = await get_price(pid)
            stock = get_stock_blocking(pid)
        return price * stock
    
    
    async def main() -> None:
        start = time.perf_counter()
        async with asyncio.TaskGroup() as tg:
            tasks = [tg.create_task(check_one(pid)) for pid in range(1, 11)]
        total = sum(t.result() for t in tasks)
        print(f"total={total}")
        report()
        print(f"elapsed={time.perf_counter() - start:.1f}")
    
    
    asyncio.run(main())

    再运行:

    text
    total=187000
    max_concurrent=5
    blocking_on_loop=10
    elapsed=12.0

    快了一些,可还要 12 秒。这是因为价格是 5 个一起等的,库存却还是一个接一个查:get_stock_blocking 每次把事件循环钉住 1 秒,10 次就是 10 秒。

  6. 把库存那一行改成交给别的线程去等:

    python
    stock = await asyncio.to_thread(get_stock_blocking, pid)
  7. 再运行:

    text
    total=187000
    max_concurrent=5
    blocking_on_loop=0
    elapsed=4.0

    10 个商品分两批,每批查价格 1 秒、查库存 1 秒,一共 4 秒。blocking_on_loop=0:库存查询都在别的线程里,事件循环没再被卡住。

  8. 选做:把 Semaphore(5) 改成 Semaphore(10),看 max_concurrent 和 elapsed 怎样变。elapsed 不一定是 2 秒:to_thread 的线程池最多 min(32, CPU 核数 + 4) 个线程,核少的电脑上,库存还是会分批查。

做不出来时

  • elapsed 还是 20 秒左右:check_one 是一个一个 await 的,没交给 TaskGroup;或者 for 循环里写成了 await check_one(pid)。
  • max_concurrent=10:Semaphore 写在了 check_one 里面(每次调用都造一个新的,等于没限),要写在函数外面,大家共用一个。
  • max_concurrent 是 5,elapsed 是 12 秒:库存还是直接调的 get_stock_blocking,见第 6 步。
  • RuntimeWarning: coroutine 'check_one' was never awaited:tg.create_task(check_one(pid)) 写成了 check_one(pid),协程造出来了,没交出去。
  • TypeError: 'int' object can't be awaited:写成了 await get_stock_blocking(pid)。同步函数不能直接 await,要用 to_thread 包。

做完了

第 7 步看到 total=187000、max_concurrent=5、blocking_on_loop=0,elapsed 在 6 秒以内,就是做对了。

做完可以删掉这个目录:

bash
rm -rf ~/hb-python/async-lab

下一个节点:第一个 FastAPI 接口。