示例工程 20-taskgroup-cancellation-contextvars
20-taskgroup-cancellation-contextvars/01-taskgroup-cancels-siblings/taskgroup_cancels_siblings.py
"""演示 TaskGroup 在一个任务失败时取消兄弟任务。"""
from __future__ import annotations
import asyncio
async def worker(name: str, delay: float, status: dict[str, str]) -> str:
try:
await asyncio.sleep(delay)
status[name] = "done"
return name
except asyncio.CancelledError:
status[name] = "cancelled"
raise
async def fail(status: dict[str, str]) -> None:
await asyncio.sleep(0.005)
status["fail"] = "raised"
raise ValueError("boom")
async def run() -> tuple[list[tuple[str, str]], str]:
status: dict[str, str] = {}
message = ""
try:
async with asyncio.TaskGroup() as group:
group.create_task(worker("slow", 0.1, status))
group.create_task(worker("fast", 0.02, status))
group.create_task(fail(status))
except* ValueError as errors:
message = str(errors.exceptions[0])
return sorted(status.items()), message
async def main() -> None:
status, message = await run()
print(f"status: {status}")
print(f"error: {message}")
if __name__ == "__main__":
asyncio.run(main())