Skip to content

Instantly share code, notes, and snippets.

@RobinDavid
Created March 29, 2018 14:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RobinDavid/0125854ef2d384480341f50a19e07912 to your computer and use it in GitHub Desktop.
Save RobinDavid/0125854ef2d384480341f50a19e07912 to your computer and use it in GitHub Desktop.
Launch a function in a proces with a timeout on the execution time.
from multiprocessing import Process, Queue
def deadline(timeout, f, *args):
queue = Queue() #using to get the result
def subproc_function(queue, f, *args):
res = f(*args)
queue.put(res)
proc = Process(target=subproc_function, args=(queue, f) +args) #creation of a process calling longfunction with the specified arguments
proc.start() #lauching the processus on another thread
try:
res = queue.get(timeout=timeout) #getting the resultat under 1 second or stop
proc.join() #proper delete if the computation has take less than timeout seconds
return res
except: #catching every exception type
proc.terminate() #kill the process
print("Task timeout exceeded")
return None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment