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 3a49dbb98c)

Co-authored-by: hetmankp <728670+hetmankp@users.noreply.github.com>
This commit is contained in:
Miss Islington (bot) 2022-10-03 14:39:44 -07:00 committed by GitHub
parent 769b9dccd2
commit a7e281150e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -591,12 +591,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()