您可以通过创建一个循环来完成此操作,该循环将等待一些超时时间,并经常检查所有进程是否已完成。如果它们还没有在指定的时间内完成,请终止所有过程:
TIMEOUT = 5
start = time.time()
while time.time() - start <= TIMEOUT:
if not any(p.is_alive() for p in procs):
# All the processes are done, break Now.
break
time.sleep(.1) # Just to avoid hogging the cpu
else:
# We only enter this if we didn't 'break' above.
print("timed out, killing all processes")
for p in procs:
p.terminate()
p.join()