I'm trying to create a timeout, where if a function doesn't finish execution in time, a default value is returned. What I have below seems like it would work, except that the KeyboardInterrupt
exception is raised in the main thread, whereas my callback function is in a separate thread.
Is there any way in Python of specifying which thread the exception is raised in?
def interrupt():
raise KeyboardInterrupt
def callback_function():
# Start 16 ms timer
timer = threading.Timer(0.016, interrupt)
timer.start()
try:
result = inconsistent_execution_time_function(data)
timer.cancel()
except KeyboardInterrupt:
print("Long execution time")
result = default
return result