@@ -414,6 +414,52 @@ reported by :meth:`asyncio.Task.cancelling`.
414414 Improved handling of simultaneous internal and external cancellations
415415 and correct preservation of cancellation counts.
416416
417+ Group Cancellation
418+ ------------------
419+
420+ Cancelling an entire task group is not natively supported by the standard
421+ library but can be achieved by adding a task to the group that raises an
422+ exception and ignoring that exception:
423+
424+ .. code-block :: python
425+
426+ import asyncio
427+ from asyncio import TaskGroup
428+
429+ class CancelTaskGroup (Exception ):
430+ """ Exception raised to cancel a task group."""
431+
432+ async def job (task_id , sleep_time ):
433+ print (f ' Task { task_id} : start ' )
434+ await asyncio.sleep(sleep_time)
435+ print (f ' Task { task_id} : done ' )
436+
437+ async def cancel_task_group ():
438+ """ A task that would cancel the group it belongs to."""
439+ raise CancelTaskGroup()
440+
441+ async def main ():
442+ try :
443+ async with TaskGroup() as group:
444+ # ... spawn some tasks ...
445+ group.create_task(job(1 , 1 ))
446+ group.create_task(job(2 , 2 ))
447+ # create a task that would cancel the group after 1.5 seconds
448+ await asyncio.sleep(1.5 )
449+ group.create_task(cancel_task_group())
450+ except * CancelTaskGroup:
451+ pass
452+
453+ asyncio.run(main())
454+
455+ Expected output:
456+
457+ .. code-block :: text
458+
459+ Task 1: start
460+ Task 2: start
461+ Task 1: done
462+
417463 Sleeping
418464========
419465
0 commit comments