Skip to content

Commit 52d8f36

Browse files
itamarocarljm
andauthored
gh-104144: Skip scheduling a done callback if a TaskGroup task completes eagerly (#104140)
Co-authored-by: Carl Meyer <carl@oddbird.net>
1 parent f3e7eb4 commit 52d8f36

File tree

2 files changed

+9
-2
lines changed

2 files changed

+9
-2
lines changed

Diff for: Lib/asyncio/taskgroups.py

+8-2
Original file line numberDiff line numberDiff line change
@@ -164,8 +164,14 @@ def create_task(self, coro, *, name=None, context=None):
164164
else:
165165
task = self._loop.create_task(coro, context=context)
166166
tasks._set_task_name(task, name)
167-
task.add_done_callback(self._on_task_done)
168-
self._tasks.add(task)
167+
# optimization: Immediately call the done callback if the task is
168+
# already done (e.g. if the coro was able to complete eagerly),
169+
# and skip scheduling a done callback
170+
if task.done():
171+
self._on_task_done(task)
172+
else:
173+
self._tasks.add(task)
174+
task.add_done_callback(self._on_task_done)
169175
return task
170176

171177
# Since Python 3.8 Tasks propagate all exceptions correctly,
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Optimize :class:`asyncio.TaskGroup` when using :func:`asyncio.eager_task_factory`. Skip scheduling done callbacks when all tasks finish without blocking.

0 commit comments

Comments
 (0)