Much like its ThreadPoolExecutor equivalent, the multiprocessing.Pool map function allows us to map every element in an iterable to a task that can be picked up by a worker in our process pool.
In this small example, we look at mapping list = [4,3,2,1] to our process pool using the said map function:
from multiprocessing import Pool
import time
def myTask(n):
time.sleep(n/2)
return n*2
def main():
print("mapping array to pool")
with Pool(4) as p:
print(p.map(myTask, [4,3,2,1]))
if __name__ == '__main__':
main()
This map function should then go on to print out the following on the console upon execution:
$ python3.6 17_mapPool.py
mapping array to pool
[8, 6, 4, 2]
However, like our apply function, each of these tasks blocks till the result is ready, so, in some cases, you may need to resort to map_async in order to achieve fully parallel asynchronous performance.