# How to cancel all tasks created within same TaskGroup

**URL:** <https://discuss.python.org/t/how-to-cancel-all-tasks-created-within-same-taskgroup/30215>\
**Category:** Python Help\
**Tags:** asyncio\
**Created:** [July 24, 2023, 6:29pm UTC](https://discuss.python.org/t/how-to-cancel-all-tasks-created-within-same-taskgroup/30215 "2023-07-24T18:29:01Z")\
**Posts on this page:** 1\
**Showing post:** 15

<div class="post-metadata">

**Author:** ![hlovatt](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/hlovatt/32/36838_2.png) [@hlovatt](https://discuss.python.org/u/hlovatt)\
**Post date:** [December 8, 2025, 1:23am UTC](https://discuss.python.org/t/how-to-cancel-all-tasks-created-within-same-taskgroup/30215/15 "2025-12-08T01:23:12Z")

</div>

How about:

```python
import asyncio
import random

async def coro(id, tasks):
    while True:
        await asyncio.sleep(0)
        if random.random() < 0.3:
            print(f"coro {id} is cancelling all coros")
            for task in tasks:
                task.cancel()
            break
        print(f"coro {id} is alive")

async def main():
    tasks = []
    async with asyncio.TaskGroup() as tg:
        tasks.append(tg.create_task(coro(0, tasks)))
        tasks.append(tg.create_task(coro(1, tasks)))

asyncio.run(main())

```

---

_[View the full topic](https://discuss.python.org/t/how-to-cancel-all-tasks-created-within-same-taskgroup/30215)._
