I wrote the following code

import multiprocessing as mp
import time


#
def f(x) :
    time.sleep(0.1)
    return pow( x, 2 )

#
my_chunksize = 10

#
if __name__ == '__main__':

    #
    po = mp.Pool( processes=2 )
    po_res = po.map_async( f, range(100), my_chunksize )

    #po.close()
    #po.join()

    #
    print po_res.get()

This is working fine. Why are the po.close() and po.join() unneeded? Why doesn't the main process die before the children processes?

有帮助吗?

解决方案

Your final:

print po_res.get()

statement blocks the main program until the map_async() is entirely finished. It's the .get() that blocks, waiting for the entire result list to be available. And that can't happen until all the work passed to map_async() has been completed and all the results returned to the main program.

Comment that statement out, and you'll see that your program exits very quickly.

That said, it's best practice to use .close() and .join() regardless.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top