| FazBrowse GitHub Viewer | Trending | | Home |
| Tools: [Download Repo ZIP] [Original HTTPS Page] |
1 parent 306368c commit 13565f1
1 file changed
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
@@ -386,6 +386,53 @@ The same special case is made for | |||
| 386 | 386 | :exc:`KeyboardInterrupt` and :exc:`SystemExit` as in the previous paragraph. | |
| 387 | 387 | ||
| 388 | 388 | ||
| 389 | + Terminating a Task Group | ||
| 390 | + ------------------------ | ||
| 391 | + | ||
| 392 | + While terminating a task group is not natively supported by the standard | ||
| 393 | + library, termination can be achieved by adding an exception-raising task | ||
| 394 | + to the task group and ignoring the raised exception: | ||
| 395 | + | ||
| 396 | + .. code-block:: python | ||
| 397 | + | ||
| 398 | + import asyncio | ||
| 399 | + from asyncio import TaskGroup | ||
| 400 | + | ||
| 401 | + class TerminateTaskGroup(Exception): | ||
| 402 | + """Exception raised to terminate a task group.""" | ||
| 403 | + | ||
| 404 | + async def force_terminate_task_group(): | ||
| 405 | + """Used to force termination of a task group.""" | ||
| 406 | + raise TerminateTaskGroup() | ||
| 407 | + | ||
| 408 | + async def job(task_id, sleep_time): | ||
| 409 | + print(f'Task {task_id}: start') | ||
| 410 | + await asyncio.sleep(sleep_time) | ||
| 411 | + print(f'Task {task_id}: done') | ||
| 412 | + | ||
| 413 | + async def main(): | ||
| 414 | + try: | ||
| 415 | + async with TaskGroup() as group: | ||
| 416 | + # spawn some tasks | ||
| 417 | + group.create_task(job(1, 0.5)) | ||
| 418 | + group.create_task(job(2, 1.5)) | ||
| 419 | + # sleep for 1 second | ||
| 420 | + await asyncio.sleep(1) | ||
| 421 | + # add an exception-raising task to force the group to terminate | ||
| 422 | + group.create_task(force_terminate_task_group()) | ||
| 423 | + except* TerminateTaskGroup: | ||
| 424 | + pass | ||
| 425 | + | ||
| 426 | + asyncio.run(main()) | ||
| 427 | + | ||
| 428 | + Expected output: | ||
| 429 | + | ||
| 430 | + .. code-block:: text | ||
| 431 | + | ||
| 432 | + Task 1: start | ||
| 433 | + Task 2: start | ||
| 434 | + Task 1: done | ||
| 435 | + | ||
| 389 | 436 | Sleeping | |
| 390 | 437 | ======== | |
| 391 | 438 | ||
| Back | FazBrowse Home | New Git URL |
0 commit comments