在pool.map_async()中检查返回的子代的数据

时间:2018-08-10 11:24:04

标签: python-3.x multiprocessing

假设我正在尝试从0-100000查找一个特殊的数字。这是我这样做的程序:

def checkNum(num):
    if num == 43582:
        print('Found!')
        return True
    return False

if __name__ == '__main__':

    thingsToCheck = []
    for i in range(0, someLargeNumber)
        thingsToCheck.append(randomInteger())

    pool = Pool(cpu_count())
    answers = pool.map_async(checkNum, thingsToCheck)
    answers.wait()
    answers = nodesPopulated.get()
    if True in answers:
        print('Answer was found!')
    else:
        print('No answer :(')

有两个输出选项:

Found!
Found!
...
Found!
Answer was found!

对于Found!可以被打印len(thingsToCheck)次或

No answer :(

但是,仅检查我们是否找到了号码,一次又一次地找到它似乎是毫无意义的,这是我想做的。因此,有没有一种方法可以在结果传入时对其进行循环,然后终止其他子级?我希望做这样的事情:(伪)

answers = pool.map_async(checkNum, thingsToCheck)
while newAnswer has come:            #run this loop when a child has finished
    answers = nodesPopulated.get()   #hopefully returns list of return values or None
    for answer in answers:
        if answer == complete:
            if True in answer:
                print('Answer was found!')
                answers.killChildren()
                quit()
print('No answer :(')

0 个答案:

没有答案