From: Miss Islington (bot) <31488909+miss-islington@users.noreply.github.com> Date: Mon, 3 Oct 2022 21:39:24 +0000 (-0700) Subject: gh-94732: Fix KeyboardInterrupt race in asyncio run_forever() (GH-97765) X-Git-Tag: v3.11.1~398 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=4420da0aefc31b066f3b0d80ceed8ce0edbcc7c2;p=thirdparty%2FPython%2Fcpython.git gh-94732: Fix KeyboardInterrupt race in asyncio run_forever() (GH-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. (cherry picked from commit 3a49dbb98ccc1b90554ed181386316efa38adfba) Co-authored-by: hetmankp <728670+hetmankp@users.noreply.github.com> --- diff --git a/Lib/asyncio/base_events.py b/Lib/asyncio/base_events.py index 7c06e48a671a..9b8167d7a139 100644 --- a/Lib/asyncio/base_events.py +++ b/Lib/asyncio/base_events.py @@ -595,12 +595,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()