alphanumeric
alphanumeric

Reputation: 19379

How to terminate multiprocessing Process on timeout

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)

edited later: this question was marked as duplicate pointing to another post that discusses the multiprocessing.Process's terminate and join methods. It does not discuss the termination on timeout.

Upvotes: 1

Views: 2562

Answers (1)

Darkonaut
Darkonaut

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

Related Questions