| @@ 16-42 (lines=27) @@ | ||
| 13 | ctx_mp_fork = multiprocessing.get_context('fork') |
|
| 14 | ||
| 15 | ||
| 16 | def exit_after(seconds, default=None): |
|
| 17 | """Exit the function if it takes more than 'second' seconds to complete. |
|
| 18 | In this case, return the value of 'default' (default: None).""" |
|
| 19 | ||
| 20 | def handler(q, func, args, kwargs): |
|
| 21 | q.put(func(*args, **kwargs)) |
|
| 22 | ||
| 23 | def decorator(func): |
|
| 24 | def wraps(*args, **kwargs): |
|
| 25 | q = ctx_mp_fork.Queue() |
|
| 26 | p = ctx_mp_fork.Process(target=handler, args=(q, func, args, kwargs)) |
|
| 27 | p.start() |
|
| 28 | p.join(timeout=seconds) |
|
| 29 | if not p.is_alive(): |
|
| 30 | return q.get() |
|
| 31 | ||
| 32 | p.terminate() |
|
| 33 | p.join(timeout=0.1) |
|
| 34 | if p.is_alive(): |
|
| 35 | # Kill in case processes doesn't terminate |
|
| 36 | # Happens with cases like broken NFS connections |
|
| 37 | p.kill() |
|
| 38 | return default |
|
| 39 | ||
| 40 | return wraps |
|
| 41 | ||
| 42 | return decorator |
|
| 43 | ||
| 44 | ||
| 45 | class Issue3290: |
|
| @@ 7-33 (lines=27) @@ | ||
| 4 | import psutil |
|
| 5 | ||
| 6 | ||
| 7 | def exit_after(seconds, default=None): |
|
| 8 | """Exit the function if it takes more than 'second' seconds to complete. |
|
| 9 | In this case, return the value of 'default' (default: None).""" |
|
| 10 | ||
| 11 | def handler(q, func, args, kwargs): |
|
| 12 | q.put(func(*args, **kwargs)) |
|
| 13 | ||
| 14 | def decorator(func): |
|
| 15 | def wraps(*args, **kwargs): |
|
| 16 | q = Queue() |
|
| 17 | p = Process(target=handler, args=(q, func, args, kwargs)) |
|
| 18 | p.start() |
|
| 19 | p.join(timeout=seconds) |
|
| 20 | if not p.is_alive(): |
|
| 21 | return q.get() |
|
| 22 | ||
| 23 | p.terminate() |
|
| 24 | p.join(timeout=0.1) |
|
| 25 | if p.is_alive(): |
|
| 26 | # Kill in case processes doesn't terminate |
|
| 27 | # Happens with cases like broken NFS connections |
|
| 28 | p.kill() |
|
| 29 | return default |
|
| 30 | ||
| 31 | return wraps |
|
| 32 | ||
| 33 | return decorator |
|
| 34 | ||
| 35 | ||
| 36 | class Issue3290: |
|