【发布时间】:2020-02-09 01:43:37
【问题描述】:
我正在使用multiprocessing 来生成task 的各个进程。如果task 花费的时间超过5 秒,我希望进程被杀死。在documentation 中,它声明了以下内容
加入([超时])
如果可选参数 timeout 为 None(默认值),则该方法会阻塞,直到调用 join() 方法的进程终止。如果 timeout 为正数,则最多阻塞 timeout 秒...
但是,在使用下面的代码进行测试时,我注意到在设置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
【问题讨论】:
标签: python multiprocessing python-multiprocessing