1

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_out), as that function can sometimes be executed in a few seconds, and in those cases the thread will always wait out the time_out.

Are there any other approaches?

Sources:

Community
  • 1
  • 1
gsagrawal
  • 2,342
  • 3
  • 24
  • 25
  • I Think threading has a Timer class.. can you use that? – User Feb 01 '13 at 13:53
  • timer class is to start a thread after certain time.here ,i want to stop the execution of thread after certain time. – gsagrawal Feb 04 '13 at 03:39
  • usually I poll - taking the current time and doing a while. Have a look at the function in line 10. https://github.com/niccokunzmann/pynet/blob/master/process/test_multi_Process.py – User Feb 05 '13 at 11:36

1 Answers1

0

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.

    def raise_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.

Talendar
  • 1,322
  • 10
  • 20
Dr. Luke
  • 1
  • 1
  • 2