diff options
author | Andrew Svetlov <andrew.svetlov@gmail.com> | 2019-06-11 15:27:30 (GMT) |
---|---|---|
committer | Miss Islington (bot) <31488909+miss-islington@users.noreply.github.com> | 2019-06-11 15:27:30 (GMT) |
commit | 65aa64fae89a24491aae84ba0329eb8f3c68c389 (patch) | |
tree | 0b1714dc7902f4ffa00c3dff4d5a4d918ec54b24 /Lib/asyncio/tasks.py | |
parent | 1f11cf9521114447b3e32e2ac88f075ffaa37555 (diff) | |
download | cpython-65aa64fae89a24491aae84ba0329eb8f3c68c389.zip cpython-65aa64fae89a24491aae84ba0329eb8f3c68c389.tar.gz cpython-65aa64fae89a24491aae84ba0329eb8f3c68c389.tar.bz2 |
bpo-36607: Eliminate RuntimeError raised by asyncio.all_tasks() (GH-13971)
If internal tasks weak set is changed by another thread during iteration.
https://bugs.python.org/issue36607
Diffstat (limited to 'Lib/asyncio/tasks.py')
-rw-r--r-- | Lib/asyncio/tasks.py | 38 |
1 files changed, 32 insertions, 6 deletions
diff --git a/Lib/asyncio/tasks.py b/Lib/asyncio/tasks.py index 95e8560..cd4832c 100644 --- a/Lib/asyncio/tasks.py +++ b/Lib/asyncio/tasks.py @@ -42,9 +42,22 @@ def all_tasks(loop=None): """Return a set of all tasks for the loop.""" if loop is None: loop = events.get_running_loop() - # NB: set(_all_tasks) is required to protect - # from https://bugs.python.org/issue34970 bug - return {t for t in list(_all_tasks) + # Looping over a WeakSet (_all_tasks) isn't safe as it can be updated from another + # thread while we do so. Therefore we cast it to list prior to filtering. The list + # cast itself requires iteration, so we repeat it several times ignoring + # RuntimeErrors (which are not very likely to occur). See issues 34970 and 36607 for + # details. + i = 0 + while True: + try: + tasks = list(_all_tasks) + except RuntimeError: + i += 1 + if i >= 1000: + raise + else: + break + return {t for t in tasks if futures._get_loop(t) is loop and not t.done()} @@ -54,9 +67,22 @@ def _all_tasks_compat(loop=None): # method. if loop is None: loop = events.get_event_loop() - # NB: set(_all_tasks) is required to protect - # from https://bugs.python.org/issue34970 bug - return {t for t in list(_all_tasks) if futures._get_loop(t) is loop} + # Looping over a WeakSet (_all_tasks) isn't safe as it can be updated from another + # thread while we do so. Therefore we cast it to list prior to filtering. The list + # cast itself requires iteration, so we repeat it several times ignoring + # RuntimeErrors (which are not very likely to occur). See issues 34970 and 36607 for + # details. + i = 0 + while True: + try: + tasks = list(_all_tasks) + except RuntimeError: + i += 1 + if i >= 1000: + raise + else: + break + return {t for t in tasks if futures._get_loop(t) is loop} def _set_task_name(task, name): |