When should we call multiprocessing.Pool.join?

PythonPython Multiprocessing

Python Problem Overview

I am using 'multiprocess.Pool.imap_unordered' as following

from multiprocessing import Pool
pool = Pool()
for mapped_result in pool.imap_unordered(mapping_func, args_iter):
    do some additional processing on mapped_result

Do I need to call pool.close or pool.join after the for loop?

Python Solutions

Solution 1 - Python

No, you don't, but it's probably a good idea if you aren't going to use the pool anymore.

Reasons for calling pool.close or pool.join are well said by Tim Peters in this SO post:

> As to Pool.close(), you should call that when - and only when - you're never going to submit more work to the Pool instance. So Pool.close() is typically called when the parallelizable part of your main program is finished. Then the worker processes will terminate when all work already assigned has completed. > It's also excellent practice to call Pool.join() to wait for the worker processes to terminate. Among other reasons, there's often no good way to report exceptions in parallelized code (exceptions occur in a context only vaguely related to what your main program is doing), and Pool.join() provides a synchronization point that can report some exceptions that occurred in worker processes that you'd otherwise never see.

Solution 2 - Python

I had the same memory issue as https://stackoverflow.com/questions/18414020/memory-usage-keep-growing-with-pythons-multiprocessing-pool when I didn't use pool.close() and pool.join() when using pool.map() with a function that calculated Levenshtein distance. The function worked fine, but wasn't garbage collected properly on a Win7 64 machine, and the memory usage kept growing out of control every time the function was called until it took the whole operating system down. Here's the code that fixed the leak:

stringList = []
for possible_string in stringArray:

pool = Pool(5)
results = pool.map(myLevenshteinFunction, stringList)

After closing and joining the pool the memory leak went away.


All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionhchView Question on Stackoverflow
Solution 1 - PythonBamcclurView Answer on Stackoverflow
Solution 2 - Pythonuser5099519View Answer on Stackoverflow