使用模块中的构件
multiprocessing:
import multiprocessingimport QueueTIMEOUT = 5def big_loop(bob): import time time.sleep(4) return bob*2def wrapper(queue, bob): result = big_loop(bob) queue.put(result) queue.close()def run_loop_with_timeout(): bob = 21 # Whatever sensible value you need queue = multiprocessing.Queue(1) # Maximum size is 1 proc = multiprocessing.Process(target=wrapper, args=(queue, bob)) proc.start() # Wait for TIMEOUT seconds try: result = queue.get(True, TIMEOUT) except Queue.Empty: # Deal with lack of data somehow result = None finally: proc.terminate() # Process data here, not in try block above, otherwise your process keeps running print resultif __name__ == "__main__": run_loop_with_timeout()
您也可以使用
Pipe/
Connection对来完成此操作,但是我对他们的API并不熟悉。更改睡眠时间或
TIMEOUT检查两种情况的行为。



