Created
January 22, 2015 13:56
-
-
Save fordhurley/dae1a012da2b3fb72291 to your computer and use it in GitHub Desktop.
Implementing a timeout in python with multiprocessing
This file contains 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
import time | |
import multiprocessing as mp | |
from Queue import Empty | |
def timed_run(func, args=(), kwargs={}, timeout=10, default=None): | |
def run_func(q): | |
result = func(*args, **kwargs) | |
q.put(result) | |
queue = mp.Queue() | |
p = mp.Process(target=run_func, args=(queue,)) | |
p.start() | |
print 'calling %s for %r seconds' % (func, timeout) | |
started_at = time.time() | |
p.join(timeout) | |
ended_at = time.time() | |
diff = round(ended_at - started_at) | |
print '%s exited after %r seconds' % (func, diff) | |
if p.is_alive(): | |
print 'terminating process %s' % p | |
p.terminate() | |
try: | |
return queue.get(False) | |
except Empty: | |
return default | |
def loop_forever(): | |
while True: | |
time.sleep(1) | |
print 'still sleeping (forever)' | |
def loop_for(seconds): | |
i = 0 | |
while i < seconds: | |
time.sleep(1) | |
print 'still sleeping (for %d seconds)' % seconds | |
i += 1 | |
return i | |
if __name__ == '__main__': | |
result = timed_run(loop_forever, timeout=5, default=-1) | |
print 'Result:', result | |
result = timed_run(loop_for, args=(10,), timeout=5, default=-1) | |
print 'Result:', result | |
result = timed_run(loop_for, args=(3,), timeout=5, default=-1) | |
print 'Result:', result | |
result = timed_run(loop_for, args=(20,), timeout=5, default=-1) | |
print 'Result:', result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: