Skip to content

Commit 8adebdc

Browse files
committed
add note about garbage collection of tasks
1 parent 0527218 commit 8adebdc

File tree

1 file changed

+20
-2
lines changed

1 file changed

+20
-2
lines changed

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

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -172,8 +172,26 @@ functions) tied to an event loop.
172172
A task also maintains a list of callback functions whose importance will become
173173
clear in a moment when we discuss :keyword:`await`.
174174
The recommended way to create tasks is via :func:`asyncio.create_task`.
175-
Creating a task automatically schedules it for execution (by adding it to the
176-
event loop's to-do list, that is, collection of jobs).
175+
176+
Creating a task automatically schedules it for execution (by adding a
177+
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.
177195

178196
Since there's only one event loop (in each thread), :mod:`!asyncio` takes care of
179197
associating the task with the event loop for you. As such, there's no need

0 commit comments

Comments
 (0)