Skip to content

Commit 62ab3f8

Browse files
committed
gh-155418: Fix TaskGroup hang when a task cancels it before suspending
1 parent 998b890 commit 62ab3f8

3 files changed

Lines changed: 15 additions & 0 deletions

File tree

Lib/asyncio/taskgroups.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,9 @@ def create_task(self, coro, **kwargs):
222222
# the current task too early. gh-128550, gh-128588
223223
self._tasks.add(task)
224224
task.add_done_callback(self._on_task_done)
225+
# gh-155418: an eager task can cancel the group before joining _tasks
226+
if self._aborting and not task.done():
227+
task.cancel()
225228
try:
226229
return task
227230
finally:

Lib/test/test_asyncio/test_taskgroups.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1154,6 +1154,16 @@ async def test_taskgroup_cancel_before_create_task(self):
11541154
with self.assertRaises(RuntimeError):
11551155
tg.create_task(asyncio.sleep(1))
11561156

1157+
async def test_taskgroup_cancel_from_child_before_first_suspension(self):
1158+
# gh-155418: an eager task can cancel the group before joining _tasks
1159+
async def child(tg):
1160+
tg.cancel()
1161+
await asyncio.sleep(10)
1162+
1163+
async with asyncio.TaskGroup() as tg:
1164+
task = tg.create_task(child(tg))
1165+
self.assertTrue(task.cancelled())
1166+
11571167
async def test_taskgroup_cancel_before_exception(self):
11581168
async def raise_exc(parent_tg: asyncio.TaskGroup):
11591169
parent_tg.cancel()
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix :class:`asyncio.TaskGroup` hang when a task cancels it before
2+
suspending.

0 commit comments

Comments
 (0)