Skip to content

Commit 5b3b697

Browse files
committed
rework task gc example.
1 parent 15aa0c5 commit 5b3b697

1 file changed

Lines changed: 19 additions & 9 deletions

File tree

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

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -208,23 +208,33 @@ It's important to be aware that the task itself is not added to the event loop,
208208
only a callback to the task is.
209209
This matters if the task object you created is garbage collected before it's
210210
called by the event loop.
211-
For example, consider this program::
211+
For example, consider this program:
212+
213+
.. code-block::
214+
:linenos:
212215
213216
async def hello():
214217
print("hello!")
215218
216219
async def main():
217-
hello_task = asyncio.create_task(hello())
218-
return
220+
asyncio.create_task(hello())
221+
# Other asynchronous instructions which run for a while
222+
# and cede control to the event loop...
223+
...
219224
220225
asyncio.run(main())
221226
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.
227+
Because there's no reference to the task object created on line 5, it *might*
228+
be garbage collected before the event loop invokes it.
229+
Despite later instructions in the coroutine ``main()`` handing control back to
230+
the event loop so it can invoke other jobs, the task which wraps the ``hello()``
231+
coroutine may never run because it's already gone!
232+
This can also happen even if a coroutine keeps a reference to a task but
233+
completes before that task finishes.
234+
When the coroutine exits, local variables go out of scope and may be subject
235+
to garbage collection.
236+
In practice, ``asyncio`` and Python's garbage collector work pretty hard to
237+
ensure this sort of thing doesn't happen.
228238
But that's no reason to be reckless!
229239

230240
=====

0 commit comments

Comments
 (0)