]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-94732: Fix KeyboardInterrupt race in asyncio run_forever() (GH-97765)
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Mon, 3 Oct 2022 21:39:44 +0000 (14:39 -0700)
committerGitHub <noreply@github.com>
Mon, 3 Oct 2022 21:39:44 +0000 (14:39 -0700)
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.
(cherry picked from commit 3a49dbb98ccc1b90554ed181386316efa38adfba)

Co-authored-by: hetmankp <728670+hetmankp@users.noreply.github.com>
Lib/asyncio/base_events.py

index 1cc26ee7ccf06a794e78b08bc57a2fa7427762d6..23849852eb98497ffcd0f21deb0a539c94dc5d9d 100644 (file)
@@ -591,12 +591,13 @@ class BaseEventLoop(events.AbstractEventLoop):
         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()