diff options
author | Andreas Grommek <76997441+agrommek@users.noreply.github.com> | 2022-06-07 08:56:09 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-06-07 08:56:09 (GMT) |
commit | 75ceae05c11461beda65e6170b67b0b42fd55cd0 (patch) | |
tree | e4e13ac71c574c5d9b584775f730ba9f494ad1a9 /Doc/library/asyncio-task.rst | |
parent | f0d0be3493fc5855eccfe0fbb3f25bf12760041f (diff) | |
download | cpython-75ceae05c11461beda65e6170b67b0b42fd55cd0.zip cpython-75ceae05c11461beda65e6170b67b0b42fd55cd0.tar.gz cpython-75ceae05c11461beda65e6170b67b0b42fd55cd0.tar.bz2 |
gh-88831: In docs for asyncio.create_task, explain why strong references to tasks are needed (GH-93258)
Co-authored-by: Ćukasz Langa <lukasz@langa.pl>
Diffstat (limited to 'Doc/library/asyncio-task.rst')
-rw-r--r-- | Doc/library/asyncio-task.rst | 19 |
1 files changed, 18 insertions, 1 deletions
diff --git a/Doc/library/asyncio-task.rst b/Doc/library/asyncio-task.rst index 8e3d49d..7796e47 100644 --- a/Doc/library/asyncio-task.rst +++ b/Doc/library/asyncio-task.rst @@ -226,7 +226,24 @@ Creating Tasks .. important:: Save a reference to the result of this function, to avoid - a task disappearing mid execution. + a task disappearing mid execution. The event loop only keeps + weak references to tasks. A task that isn't referenced elsewhere + may get garbage-collected at any time, even before it's done. + For reliable "fire-and-forget" background tasks, gather them in + a collection:: + + background_tasks = set() + + for i in range(10): + task = asyncio.create_task(some_coro(param=i)) + + # Add task to the set. This creates a strong reference. + background_tasks.add(task) + + # To prevent keeping references to finished tasks forever, + # make each task remove its own reference from the set after + # completion: + task.add_done_callback(background_tasks.discard) .. versionadded:: 3.7 |