示例工程 20-taskgroup-cancellation-contextvars
20-taskgroup-cancellation-contextvars/03-semaphore-throttle/README.md
# 03 · semaphore-throttle
**演示**:20 个任务共用一个 `Semaphore(5)`,峰值并发被限制在 5;`async with` 保证异常时也释放。
**运行**:
```sh
uv run python examples/20-taskgroup-cancellation-contextvars/03-semaphore-throttle/semaphore_throttle.py
```
**预期输出**(3.12.9):
```text
completed: 20
peak: 5
```
**依赖**:仅标准库。
**注意**:Semaphore 限制的是「同时进入临界区的协程数」,适合保护数据库连接/下游配额;它不是线程锁,不保证临界区不被打断。