Skip to content

Commit 9d3828d

Browse files
committed
re arrange note on task gc.
1 parent a8fa7f6 commit 9d3828d

File tree

1 file changed

+23
-21
lines changed

1 file changed

+23
-21
lines changed

Doc/howto/a-conceptual-overview-of-asyncio.rst

Lines changed: 23 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -175,27 +175,6 @@ The recommended way to create tasks is via :func:`asyncio.create_task`.
175175

176176
Creating a task automatically schedules it for execution (by adding a
177177
callback to run it in the event loop's to-do list, that is, collection of jobs).
178-
It's important to be aware that the task itself is not added to the event loop.
179-
This matters if the task object you created is garbage collected before it's
180-
called by the event loop.
181-
For example, consider this program::
182-
183-
async def hello():
184-
print("hello!")
185-
186-
async def main():
187-
hello_task = asyncio.create_task(hello())
188-
return
189-
190-
asyncio.run(main())
191-
192-
Because the coroutine ``main()`` exits before awaiting the task and no other
193-
references to the task are made, the task object ``hello_task`` *might* be
194-
garbage collected before the event loop invokes it.
195-
That example still actually ends up running ``hello_task``, because
196-
``asyncio`` and Python's garbage collector work pretty hard to ensure this
197-
sort of thing doesn't happen.
198-
But that's no reason to be reckless!
199178

200179
Since there's only one event loop (in each thread), :mod:`!asyncio` takes care of
201180
associating the task with the event loop for you. As such, there's no need
@@ -225,6 +204,29 @@ For example, many async programs follow this setup::
225204
# coroutine main() finishes.
226205
print("coroutine main() is done!")
227206

207+
It's important to be aware that the task itself is not added to the event loop,
208+
only a callback to the task is.
209+
This matters if the task object you created is garbage collected before it's
210+
called by the event loop.
211+
For example, consider this program::
212+
213+
async def hello():
214+
print("hello!")
215+
216+
async def main():
217+
hello_task = asyncio.create_task(hello())
218+
return
219+
220+
asyncio.run(main())
221+
222+
Because the coroutine ``main()`` exits before awaiting the task and no other
223+
references to the task are made, the task object ``hello_task`` *might* be
224+
garbage collected before the event loop invokes it.
225+
That example still actually ends up running ``hello_task``, because
226+
``asyncio`` and Python's garbage collector work pretty hard to ensure this
227+
sort of thing doesn't happen.
228+
But that's no reason to be reckless!
229+
228230
=====
229231
await
230232
=====

0 commit comments

Comments
 (0)