首页 > 解决方案 > Python - 多处理 - 超时 - 多次尝试加入()

问题描述

我正在编写脚本来检查几个挂载点,如果它们工作正常。挂载点可能发生的问题之一是它挂起,并且该挂载点的签出也挂起。

我正在尝试使用 multiprocessing.Process 模块超时,但它没有按预期工作。我想要得到的是选项:对于每个结帐(每个进程)尝试检查挂载点,但如果结帐(进程)挂起超过 2 秒,则终止该进程。因此,即使有 10 个进程,每个进程都将超时设置为 2 秒,脚本应该不会超过 ~2,5 秒,但它的工作方式有些奇怪,它不会在超时后杀死进程。

目前的脚本是:

import time
from multiprocessing import Process, Array, Lock, Manager, TimeoutError
from random import randrange

def square_numbers(lock, file, manager_dict, counter):
    value = randrange(10)
    print(f'Process {counter} sleep: {value}')
    time.sleep(value)
    with lock:
        manager_dict[file] = True

if __name__ == "__main__":
    lock = Lock()
    processes = list()
    manager = Manager()
    manager_dict = manager.dict()
    files = ['1.txt', '2.txt', '3.txt', '4.txt','5.txt']

    for counter, file in enumerate(files):
        process = Process(target=square_numbers, args=(lock, file, manager_dict, counter))
        processes.append(process)

    for process in processes:
        process.start()

    for process in processes:
        try:
            process.join(1)
            process.terminate()
        except TimeoutError:
            print('Terminated')

    print(manager_dict)

这会产生近似准确的输出(但仍然太长):

#1

Process 0 sleep: 9
Process 1 sleep: 4
Process 2 sleep: 0
Process 3 sleep: 1
Process 4 sleep: 9
{'3.txt': True, '4.txt': True}

real    0m3.074s
user    0m0.050s
sys     0m0.029s

#2

Process 0 sleep: 3
Process 1 sleep: 1
Process 2 sleep: 6
Process 3 sleep: 9
Process 4 sleep: 0
{'5.txt': True, '2.txt': True}

real    0m3.072s
user    0m0.055s
sys     0m0.022s

#3

Process 0 sleep: 7
Process 1 sleep: 3
Process 2 sleep: 5
Process 3 sleep: 3
Process 4 sleep: 8
{'4.txt': True}

real    0m4.075s
user    0m0.049s
sys     0m0.029s

但是,如果我增加 join() 中的值,例如 join(3),它会在荒谬的时间内工作 3 秒后不会杀死任何进程,它只会过滤持续时间超过 3 秒的进程的输出(或1 在上面的例子中):

Process 0 sleep: 7
Process 1 sleep: 8
Process 2 sleep: 9
Process 3 sleep: 2
Process 4 sleep: 9
{'4.txt': True}

real    0m12.090s
user    0m0.061s
sys     0m0.022s

我对上面的期望:杀死每个存在超过 3 秒的进程,这意味着杀死进程:0、1、2、4。

在 join() 的 x 秒后,我必须做什么才能立即杀死这个进程?

标签: pythonjoinprocessmultiprocessingtimeout

解决方案


推荐阅读