How to do it…

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:

  1. Import the multiprocessing library:
import multiprocessing
  1. 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__':
  1. The parameter inputs are a list of integers from 0 to 100:
    inputs = list(range(0,100))
  1. The total number of parallel processes is 4:
    pool = multiprocessing.Pool(processes=4)
  1. The pool.map method submits to the process pool as separate tasks:
    pool_outputs = pool.map(function_square, inputs)
pool.close()
pool.join()
  1. 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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset