Skip to content

Commit a7e2811

Browse files
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 3a49dbb) Co-authored-by: hetmankp <[email protected]>
1 parent 769b9dc commit a7e2811

File tree

1 file changed

+4
-3
lines changed

1 file changed

+4
-3
lines changed

Lib/asyncio/base_events.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -591,12 +591,13 @@ def run_forever(self):
591591
self._check_closed()
592592
self._check_running()
593593
self._set_coroutine_origin_tracking(self._debug)
594-
self._thread_id = threading.get_ident()
595594

596595
old_agen_hooks = sys.get_asyncgen_hooks()
597-
sys.set_asyncgen_hooks(firstiter=self._asyncgen_firstiter_hook,
598-
finalizer=self._asyncgen_finalizer_hook)
599596
try:
597+
self._thread_id = threading.get_ident()
598+
sys.set_asyncgen_hooks(firstiter=self._asyncgen_firstiter_hook,
599+
finalizer=self._asyncgen_finalizer_hook)
600+
600601
events._set_running_loop(self)
601602
while True:
602603
self._run_once()

0 commit comments

Comments
 (0)