Skip to content Skip to sidebar Skip to footer

Python , Timeout On A Function On Child Thread Without Using Signal And Thread.join

I want to add a timeout on one function which is getting called inside a child thread. I can't use a signal, as a signal should be on the main thread. I can't use thread.join(time_

Solution 1:

You can use a little known ctyps hack to raise a TimeoutError targeting a specific thread. I made a non_blocking timeout script using this method and just released it on GitHub: https://github.com/levimluke/PyTimeoutAfter

It's SUPER simple to implement, but technically complex.

defraise_caller(self):
        ret = ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(self._caller_thread._ident), ctypes.py_object(self._exception))
        if ret == 0:
            raise ValueError("Invalid thread ID")
        elif ret > 1:
            ctypes.pythonapi.PyThreadState_SetAsyncExc(self._caller_thread._ident, NULL)
            raise SystemError("PyThreadState_SetAsyncExc failed")

https://github.com/levimluke/PyTimeoutAfter/blob/main/timeout_after.py#L47

I use a class object and save the calling thread to, that way I can raise an exception in the parent class from within the timed child thread.

Post a Comment for "Python , Timeout On A Function On Child Thread Without Using Signal And Thread.join"