In some code I’m working on I want to put a 10 second timeout on a function call. If the function doesn’t return in 10 seconds I just want to terminate the function and return None. Here’s the code I came up with using multiprocessing.Pool:
import multiprocessing as mp pool = mp.Pool(1, maxtasksperchild=1) result = pool.apply_async(function, (arg1,)) pool.close() try: s = result.get(10) except mp.TimeoutError: pool.terminate() return None
This seems to work but I’m curious if there’s a standard Python pattern for this sort of thing?