[英]How to terminate multiprocessing Process on timeout
The multiprocessing proc
is terminated here using proc.terminate()
command after 5 seconds the proc
is started. 多处理proc
使用此结束proc.terminate()
的5秒后命令proc
开始。 I am using while proc.is_alive()
loop to make things done. 我正在使用while proc.is_alive()
循环来完成任务。 I wonder if there is another way to terminate proc on timeout. 我想知道是否还有另一种方法可以在超时时终止proc。
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. 稍后编辑:此问题被标记为重复,指向另一篇讨论多处理的帖子。进程的terminate
和join
方法。 It does not discuss the termination on timeout. 它没有讨论超时终止。 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. 您可以使用带有timeout
参数的Process.join
在指定的时间里阻止调用线程(在您的示例中为父进程的MainThread)。 .join
will await a possible process-exit for up to timeout
seconds, after which it will unblock. .join
将等待可能的进程退出,直到timeout
秒,之后它将取消阻止。 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 (eg queues) with other processes because that will lead to deadlocks when the terminated process holds locks at that moment. 这意味着它不应与其他进程共享资源(例如队列),因为当终止的进程此时持有锁时,这将导致死锁。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.