from multiprocessing import Pool # Define a function to be called on each element of the iterable def square(n): return n ** 2 if __name__ == '__main__': # Create a Pool object with 4 worker processes with Pool(processes=4) as pool: # Call the square function on each element of the list in parallel results = pool.map(square, [1, 2, 3, 4, 5]) print(results)
from multiprocessing import Pool # Define a function to be called asynchronously def square(n): return n ** 2 if __name__ == '__main__': # Create a Pool object with 4 worker processes with Pool(processes=4) as pool: # Call the square function asynchronously on each element of the list results = [pool.apply_async(square, (i,)) for i in range(1, 6)] # Retrieve the results output = [r.get() for r in results] print(output)In this example, the Pool.apply_async() method is used to call the square() function asynchronously on each element of the list. The results are then retrieved by calling the get() method on each Process object returned by Pool.apply_async(). Package Library: multiprocessing.