[Python-checkins] gh-94732: Fix KeyboardInterrupt race in asyncio run_forever() (#97765)

gvanrossum webhook-mailer at python.org
Mon Oct 3 16:34:45 EDT 2022


https://github.com/python/cpython/commit/3a49dbb98ccc1b90554ed181386316efa38adfba
commit: 3a49dbb98ccc1b90554ed181386316efa38adfba
branch: main
author: hetmankp <728670+hetmankp at users.noreply.github.com>
committer: gvanrossum <gvanrossum at gmail.com>
date: 2022-10-03T13:34:35-07:00
summary:

gh-94732: Fix KeyboardInterrupt race in asyncio run_forever() (#97765)

Ensure that the event loop's `_thread_id` attribute and the asyncgen hooks set by `sys.set_asyncgen_hooks()` are always restored no matter where a KeyboardInterrupt exception is raised.

files:
M Lib/asyncio/base_events.py

diff --git a/Lib/asyncio/base_events.py b/Lib/asyncio/base_events.py
index 2df9dcac8f72..66202f09794d 100644
--- a/Lib/asyncio/base_events.py
+++ b/Lib/asyncio/base_events.py
@@ -606,12 +606,13 @@ def run_forever(self):
         self._check_closed()
         self._check_running()
         self._set_coroutine_origin_tracking(self._debug)
-        self._thread_id = threading.get_ident()
 
         old_agen_hooks = sys.get_asyncgen_hooks()
-        sys.set_asyncgen_hooks(firstiter=self._asyncgen_firstiter_hook,
-                               finalizer=self._asyncgen_finalizer_hook)
         try:
+            self._thread_id = threading.get_ident()
+            sys.set_asyncgen_hooks(firstiter=self._asyncgen_firstiter_hook,
+                                   finalizer=self._asyncgen_finalizer_hook)
+
             events._set_running_loop(self)
             while True:
                 self._run_once()



More information about the Python-checkins mailing list