Created
March 29, 2018 14:52
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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