Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 13565f1

Browse files
[3.12] gh-108951: Document how to terminate an asyncio.TaskGroup (GH-123837) (#123957)
gh-108951: Document how to terminate an asyncio.TaskGroup (GH-123837) We don't want to add another API, since the recipe is straightforward and rarely needed. The advantage is that we could backport this to the earliest Python version that has taskgroups (3.11, alas in security mode already, so we'll just do 3.12 and 3.13). (cherry picked from commit ef05801) Co-authored-by: Bénédikt Tran <[email protected]>
1 parent 306368c commit 13565f1

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

Doc/library/asyncio-task.rst

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -386,6 +386,53 @@ The same special case is made for
386386
:exc:`KeyboardInterrupt` and :exc:`SystemExit` as in the previous paragraph.
387387

388388

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+
389436
Sleeping
390437
========
391438

0 commit comments

Comments
 (0)