]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-104144: Skip scheduling a done callback if a TaskGroup task completes eagerly...
authorItamar Ostricher <itamarost@gmail.com>
Fri, 5 May 2023 23:44:03 +0000 (16:44 -0700)
committerGitHub <noreply@github.com>
Fri, 5 May 2023 23:44:03 +0000 (16:44 -0700)
Co-authored-by: Carl Meyer <carl@oddbird.net>
Lib/asyncio/taskgroups.py
Misc/NEWS.d/next/Library/2023-05-03-16-51-53.gh-issue-104144.653Q0P.rst [new file with mode: 0644]

index 0fdea3697ece3d600ee3c467000ba091e664d971..06b2e0db86a1fe59010132e5339204da0dbf3d9d 100644 (file)
@@ -164,8 +164,14 @@ class TaskGroup:
         else:
             task = self._loop.create_task(coro, context=context)
         tasks._set_task_name(task, name)
-        task.add_done_callback(self._on_task_done)
-        self._tasks.add(task)
+        # optimization: Immediately call the done callback if the task is
+        # already done (e.g. if the coro was able to complete eagerly),
+        # and skip scheduling a done callback
+        if task.done():
+            self._on_task_done(task)
+        else:
+            self._tasks.add(task)
+            task.add_done_callback(self._on_task_done)
         return task
 
     # Since Python 3.8 Tasks propagate all exceptions correctly,
diff --git a/Misc/NEWS.d/next/Library/2023-05-03-16-51-53.gh-issue-104144.653Q0P.rst b/Misc/NEWS.d/next/Library/2023-05-03-16-51-53.gh-issue-104144.653Q0P.rst
new file mode 100644 (file)
index 0000000..59870de
--- /dev/null
@@ -0,0 +1 @@
+Optimize :class:`asyncio.TaskGroup` when using :func:`asyncio.eager_task_factory`. Skip scheduling done callbacks when all tasks finish without blocking.