我正在使用multiprocessing
来生成task
的各个进程。如果task
时间超过5
秒,我希望终止进程。在文档中,它指出以下内容
加入([超时](
如果可选参数超时为 None(默认值(,则该方法将一直阻塞,直到调用其 join(( 方法的进程终止。如果超时是正数,则最多阻止超时秒数...
但是,在使用以下代码进行测试时,我注意到该进程在设定的5
秒后并未终止。
import time
import multiprocessing as mp
from random import randint, seed
import os
def task(i):
x = randint(0, 20)
pid = os.getpid()
print("{}. (PID: {}) sleeping for {} seconds".format(i, pid, x))
time.sleep(x)
print("{}. (PID: {}) slept for {} seconds".format(i, pid, x))
if __name__ == '__main__':
ctx = mp.get_context() # use system default
for i in range(10):
seed(i) # set random state
p = ctx.Process(target = task, args = (i,))
p.start()
p.join(5) # terminate after 5 seconds
我是否误解了此参数的用法?有没有另一种方法可以获得预期的结果?
结果
0. (PID: 12568) sleeping for 4 seconds
0. (PID: 12568) slept for 4 seconds
1. (PID: 6396) sleeping for 18 seconds
2. (PID: 8520) sleeping for 9 seconds
3. (PID: 11192) sleeping for 14 seconds
2. (PID: 8520) slept for 9 seconds
4. (PID: 9336) sleeping for 9 seconds
1. (PID: 6396) slept for 18 seconds
5. (PID: 596) sleeping for 4 seconds
3. (PID: 11192) slept for 14 seconds
5. (PID: 596) slept for 4 seconds
4. (PID: 9336) slept for 9 seconds
6. (PID: 2920) sleeping for 4 seconds
6. (PID: 2920) slept for 4 seconds
7. (PID: 11128) sleeping for 14 seconds
8. (PID: 14164) sleeping for 14 seconds
9. (PID: 9332) sleeping for 9 seconds
7. (PID: 11128) slept for 14 seconds
8. (PID: 14164) slept for 14 seconds
9. (PID: 9332) slept for 9 seconds
正如您所注意到的,p.join
不会在超时后终止子进程,只是阻塞指定的时间(最多(,然后继续他的流,而无需再等待子进程。
如果您希望在超时后杀死它们,您需要做的就是在进程中显式调用terminate()
:
p.join(5)
p.terminate()