@@ -103,6 +103,29 @@ To actually run a coroutine, asyncio provides three main mechanisms:
103
103
world
104
104
finished at 17:14:34
105
105
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
+
106
129
107
130
.. _asyncio-awaitables :
108
131
@@ -223,6 +246,11 @@ Creating Tasks
223
246
:exc: `RuntimeError ` is raised if there is no running loop in
224
247
current thread.
225
248
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
+
226
254
.. important ::
227
255
228
256
Save a reference to the result of this function, to avoid
@@ -254,6 +282,27 @@ Creating Tasks
254
282
Added the *context * parameter.
255
283
256
284
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
+
257
306
Sleeping
258
307
========
259
308
0 commit comments