简体   繁体   English

如何在 Python 多处理模块中使用 Pool.join()?

[英]How to use Pool.join() in Python multiprocessing module?

Here is the code:这是代码:

def function(index):
    print('start process '+str(index))
    time.sleep(1)
    print('end process '+str(index))
    return str(index)

if __name__ == '__main__':
    pool = Pool(processes=3)   
    for i in range(4):
        res = pool.apply_async(function,args=(i,)) 
        print(res.get())
    pool.close()
    print('done')

and the output:和输出:

start process 0
end process 0
0
start process 1
end process 1
1
start process 2
end process 2
2
start process 3
end process 3
3
done

In my opinion, if the I don't use the pool.join(), the code should only print 'done' and that's it, because the function of pool.join() is 'Wait for the worker processes to exit', but now without pool.join(), it get the same result.在我看来,如果我不使用 pool.join(),代码应该只打印'done',就是这样,因为 pool.join() 的功能是'等待工作进程退出',但现在没有 pool.join(),它得到了相同的结果。 I really don't understand.我真的不明白。

In your code, the method get() has the same effect as join() .在您的代码中,方法get()join() ) 具有相同的效果。 It also waits for the process to finish because you want to get the result of it.它还等待该过程完成,因为您想获得它的结果。

If you remove it from your code, you will see the 'done' being printed first:如果您从代码中删除它,您将首先看到“完成”打印:

done
start process 0

res.get waits for the process to finish (how else would it get the return value?) which means that process 0 must finish before process 1 can start, and so on. res.get等待进程完成(否则它将如何获得返回值?)这意味着进程 0 必须在进程 1 开始之前完成,依此类推。

Remove res.get and you won't see the processes finish.删除res.get并且您不会看到进程完成。 Move res.get to a separate loop after the first one and you'll see they all start before any of them finish.res.get移至第一个循环之后的单独循环,您会看到它们都在其中任何一个完成之前开始。

Also check out Pool.map .另请查看Pool.map

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM