8000 GH-90908: Document TaskGroup · python/cpython@4747a9a · GitHub
[go: up one dir, main page]

Skip to content

Commit 4747a9a

Browse files
committed
GH-90908: Document TaskGroup
1 parent edb10ca commit 4747a9a

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

Doc/library/asyncio-task.rst

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,29 @@ To actually run a coroutine, asyncio provides three main mechanisms:
103103
world
104104
finished at 17:14:34
105105

106+
* The :class:`asyncio.TaskGroup` class provides a more modern
107+
alternative to :func:`create_task`.
108+
Using this API the last example becomes::
109+
110+
async def main():
111+
async with asyncio.TaskGroup() as tg:
112+
task1 = tg.create_task(
113+
say_after(1, 'hello'))
114+
115+
task2 = tg.create_task(
116+
say_after(2, 'world'))
117+
118+
print(f"started at {time.strftime('%X')}")
119+
120+
# The wait is implicit when the context manager exits.
121+
122+
print(f"finished at {time.strftime('%X')}")
123+
124+
The timing and output should be the same as for the previous version.
125+
126+
.. versionchanged:: 3.11
127+
Added :class:`asyncio.TaskGroup`.
128+
106129

107130
.. _asyncio-awaitables:
108131

@@ -223,6 +246,11 @@ Creating Tasks
223246
:exc:`RuntimeError` is raised if there is no running loop in
224247
current thread.
225248

249+
.. note::
250+
251+
:meth:`asyncio.TaskGroup.create_task` is a newer alternative
252+
that allows for convenient waiting for a group of related tasks.
253+
226254
.. important::
227255

228256
Save a reference to the result of this function, to avoid
@@ -254,6 +282,27 @@ Creating Tasks
254282
Added the *context* parameter.
255283

256284

285+
Task Groups
286+
===========
287+
288+
Task groups combine a task creation API with a convenient
289+
and reliable API to wait for completion of all tasks in the group.
290+
291+
.. class:: TaskGroup()
292+
293+
An :ref:`asynchronous context manager <async-context-managers>`
294+
holding a group of tasks.
295+
Tasks can be added to the group using the :meth:`create_task` method.
296+
All tasks are awaited when the context manager exits.
297+
298+
.. versionadded:: 3.11
299+
300+
.. method:: create_tasks(coro, *, name=None, context=None)
301+
302+
Create a task in this task group.
303+
The API is the same as the :func:`asyncio.create_task` function.
304+
305+
257306
Sleeping
258307
========
259308

0 commit comments

Comments
 (0)
0