如果孩子或工人在多处理过程中出现异常,如何停止父母?

我想实现两件事: 1)让父母活着直到孩子/工人完成 2)如果孩子/工人发生异常,则父母应在该异常之后停止。发生异常后,它不应运行其余的工作程序。

我已经编写了代码,但无法获得所需的内容。

def waitTime(ds,index):
    try:
        if index == 3:
            index = 15
        ds[index] = 'WORKED!!!'
    except:
        global isException
        isException = True


if __name__ == '__main__':
    isException = False
    ds = multiprocessing.Manager().list([None]*5)
    new = []
    for i in range(1,len(ds)+1):
        temp = multiprocessing.Process(target=waitTime,args=(ds,i-1))
        new.append(temp)
        temp.start()
        temp.join()
        if isException:
            break

    print(ds)

我的预期结果是:['WORKED !!!','WORKED !!!','WORKED !!!',None,None]

我的实际结果是:['WORKED !!!','WORKED !!!','WORKED !!!','WORKED !!!','WORKED !!!']

wakal 回答:如果孩子或工人在多处理过程中出现异常,如何停止父母?

您在这里有几个问题。首先,您实际上没有引发异常,因此永远不会触发您的工作程序中的exception子句。其次,全局变量不在流程之间传递-为此,您需要另一位经理。

考虑一下:

def waitTime(ds,isException,index):
    try:
        if index == 3:
            index = 15
            raise IndexError
        ds[index] = 'WORKED!!!'
    except IndexError:
        isException.value = 1


if __name__ == '__main__':
    isException = multiprocessing.Manager().Value("h",0)
    ds = multiprocessing.Manager().list([None]*5)
    new = []
    for i in range(1,len(ds)+1):
        temp = multiprocessing.Process(target=waitTime,args=(ds,i-1))
        new.append(temp)
        temp.start()
        temp.join()
        if isException.value == 1:
            break

    print(ds)

现在,我们引发IndexError并捕获它。您的isException现在是另一个经理,用于在您的流程之间传递价值。它不一定非常优雅,但可以。

,

全局变量不是在多进程之间共享,而是在线程中。您必须使用多处理模块提供的Value,Queue,Lock。

import multiprocessing
from multiprocessing import Value

v = Value('i',0) # where i means integer type,0 is default value


def waitTime(ds,index):
    try:
        if index == 3:
            index = 15
        ds[index] = 'WORKED!!!'
    except:
        v.value = 1 # v.value to assign integer


if __name__ == '__main__':
    isException = False
    ds = multiprocessing.Manager().list([None] * 5)
    new = []
    for i in range(1,len(ds) + 1):

       temp = multiprocessing.Process(target=waitTime,i - 1))
       new.append(temp)
       temp.start()
       temp.join()
       if v.value == 1:
           v.value = 0
           break

output:
['WORKED!!!','WORKED!!!',None,None]
本文链接:https://www.f2er.com/3153407.html

大家都在问