summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>2022-06-07 10:14:25 (GMT)
committerGitHub <noreply@github.com>2022-06-07 10:14:25 (GMT)
commitc7b5a2d5eafd40d2dd242383b4db7c15d26e8fbc (patch)
tree2d120056359be58d294ff7e5dd269bcb11e4648d
parent9204364e4095bcf6c0b2471d4ed8546d8748b44b (diff)
downloadcpython-c7b5a2d5eafd40d2dd242383b4db7c15d26e8fbc.zip
cpython-c7b5a2d5eafd40d2dd242383b4db7c15d26e8fbc.tar.gz
cpython-c7b5a2d5eafd40d2dd242383b4db7c15d26e8fbc.tar.bz2
gh-88831: In docs for asyncio.create_task, explain why strong references to tasks are needed (GH-93258) (GH-93567)
Co-authored-by: Ɓukasz Langa <lukasz@langa.pl> (cherry picked from commit 75ceae05c11461beda65e6170b67b0b42fd55cd0) Co-authored-by: Andreas Grommek <76997441+agrommek@users.noreply.github.com>
-rw-r--r--Doc/library/asyncio-task.rst19
-rw-r--r--Misc/NEWS.d/next/Documentation/2022-05-26-14-51-25.gh-issue-88831.5Cccr5.rst1
2 files changed, 19 insertions, 1 deletions
diff --git a/Doc/library/asyncio-task.rst b/Doc/library/asyncio-task.rst
index dc09286..e535a5b 100644
--- a/Doc/library/asyncio-task.rst
+++ b/Doc/library/asyncio-task.rst
@@ -262,7 +262,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
diff --git a/Misc/NEWS.d/next/Documentation/2022-05-26-14-51-25.gh-issue-88831.5Cccr5.rst b/Misc/NEWS.d/next/Documentation/2022-05-26-14-51-25.gh-issue-88831.5Cccr5.rst
new file mode 100644
index 0000000..983bea9
--- /dev/null
+++ b/Misc/NEWS.d/next/Documentation/2022-05-26-14-51-25.gh-issue-88831.5Cccr5.rst
@@ -0,0 +1 @@
+Augmented documentation of asyncio.create_task(). Clarified the need to keep strong references to tasks and added a code snippet detailing how to to this.