This example shows you how to implement a process pool to perform a parallel application. We create a pool of four processes and then we use the pool's map method to perform a simple function:
- Import the multiprocessing library:
import multiprocessing
- The Pool method applies function_square to the input element to perform a simple calculation:
def function_square(data):
result = data*data
return result
if __name__ == '__main__':
- The parameter inputs are a list of integers from 0 to 100:
inputs = list(range(0,100))
- The total number of parallel processes is 4:
pool = multiprocessing.Pool(processes=4)
- The pool.map method submits to the process pool as separate tasks:
pool_outputs = pool.map(function_square, inputs)
pool.close()
pool.join()
- The result of the calculation is stored in pool_outputs:
print ('Pool :', pool_outputs)
It is important to note that the result of the pool.map() method is equivalent to Python's built-in map() function, except that the processes run in parallel.