timeout: Minor comment cleanups.

We remove the StackOverflow link because it is now so dated as to be
irrelevant -- it does not use `self.ident`, and cargo-cults the return
value of PyThreadState_SetAsyncExc.
This commit is contained in:
Alex Vandiver 2022-04-05 11:39:12 -07:00 committed by Tim Abbott
parent 3af2c8d9a3
commit 04159a674c
1 changed files with 9 additions and 11 deletions

View File

@ -56,12 +56,12 @@ def timeout(timeout: float, func: Callable[[], ResultT]) -> ResultT:
self.exc_info = sys.exc_info() self.exc_info = sys.exc_info()
def raise_async_timeout(self) -> None: def raise_async_timeout(self) -> None:
# Called from another thread. # This function is called from another thread; we attempt
# Attempt to raise a TimeoutExpired in the thread represented by 'self'. # to raise a TimeoutExpired in _this_ thread.
assert self.ident is not None # Thread should be running; c_long expects int assert self.ident is not None
tid = ctypes.c_long(self.ident)
ctypes.pythonapi.PyThreadState_SetAsyncExc( ctypes.pythonapi.PyThreadState_SetAsyncExc(
tid, ctypes.py_object(TimeoutExpired) ctypes.c_long(self.ident),
ctypes.py_object(TimeoutExpired),
) )
thread = TimeoutThread() thread = TimeoutThread()
@ -69,11 +69,8 @@ def timeout(timeout: float, func: Callable[[], ResultT]) -> ResultT:
thread.join(timeout) thread.join(timeout)
if thread.is_alive(): if thread.is_alive():
# Gamely try to kill the thread, following the dodgy approach from # We need to retry, because an async exception received while
# https://stackoverflow.com/a/325528/90777 # the thread is in a system call is simply ignored.
#
# We need to retry, because an async exception received while the
# thread is in a system call is simply ignored.
for i in range(10): for i in range(10):
thread.raise_async_timeout() thread.raise_async_timeout()
time.sleep(0.1) time.sleep(0.1)
@ -94,5 +91,6 @@ def timeout(timeout: float, func: Callable[[], ResultT]) -> ResultT:
if thread.exc_info[1] is not None: if thread.exc_info[1] is not None:
# Died with some other exception; re-raise it # Died with some other exception; re-raise it
raise thread.exc_info[1].with_traceback(thread.exc_info[2]) raise thread.exc_info[1].with_traceback(thread.exc_info[2])
assert thread.result is not None # assured if above did not reraise
assert thread.result is not None
return thread.result return thread.result