Reputation: 19379
The multiprocessing proc
is terminated here using proc.terminate()
command after 5 seconds the proc
is started. I am using while proc.is_alive()
loop to make things done. I wonder if there is another way to terminate proc on timeout.
import time, multiprocessing
def process():
while True:
print '...sleeping %s' % time.time()
time.sleep(1)
proc = multiprocessing.Process(target=process)
proc.start()
timeout = 5
start_time = time.time()
while proc.is_alive():
if time.time() - start_time > timeout:
print 'terminating proc on timeout'
proc.terminate()
time.sleep(1)
terminate
and join
methods. It does not discuss the termination on timeout.Upvotes: 1
Views: 2562
Reputation: 21694
You can use Process.join
with it's timeout
argument to block the calling thread (in your example the MainThread in the parent process) for the specified time. .join
will await a possible process-exit for up to timeout
seconds, after which it will unblock. This enables you to write:
import time, multiprocessing
def process():
while True:
print('...sleeping %s' % time.time())
time.sleep(1)
if __name__ == '__main__':
proc = multiprocessing.Process(target=process)
proc.start()
proc.join(timeout=5)
proc.terminate()
Make sure your process is actually suited for being terminated that way. This means it shouldn't share resources (e.g. queues) with other processes because that will lead to deadlocks when the terminated process holds locks at that moment.
Upvotes: 6