Your model.predict()
method is CPU bound operation probably. In Linux, you can use signal mechanism that will interrupt your current operation, but Windows OS has no all POSIX signal features, so we can use thread
or multiprocess
to interrupt/terminate
immediately some operation. Python
gives a good option to terminate a thread using ctypes.pythonapi.PyThreadState_SetAsyncExc
, but this will not terminate the thread before the I/O
(if thread blocked) operation is finished
Here is a simple example :
import threading
import ctypes
import time
class TimeoutException(Exception):
pass
def f(arg):
while 1:
time.sleep(1)
print("hello")
class Timeout(threading.Thread):
def __init__(self,func,arg,timeout):
self.func = func
self.arg = arg
self.thread_ident = None
self.output = None
self.wait_for_finish = threading.Event()
threading.Thread.__init__(self)
self.killer = threading.Timer(timeout, self.raise_exception)
self.start()
self.wait_for_finish.wait()
def raise_exception(self):
ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(self.thread_ident),
ctypes.py_object(TimeoutException))
def run(self):
self.thread_ident = threading.get_ident()
self.killer.start()
try:
self.output = self.func(self.arg)
except TimeoutException:
self.output = "Timeout exception"
finally:
self.wait_for_finish.set()
self.killer.cancel()
output = Timeout(func=f, arg=5, timeout = 5).output
print(output)
You can also look at this