Using Pool and Map

suggest change
from multiprocessing import Pool

def cube(x):
    return x ** 3
if __name__ == "__main__":
    pool = Pool(5)
    result = pool.map(cube, [0, 1, 2, 3])

Pool is a class which manages multiple worker processes behind the scenes and lets you use them. Create it under if __name__ == "__main__", as this sample does. That guard is required when the start method is spawn, the default on Windows and macOS.

Pool(5) creates a new Pool with 5 processes, and pool.map works just like map but it uses multiple processes (the number set when creating the pool).

Similar results can be achieved using map_async, apply and apply_async which can be found in the documentation.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents