import multiprocessing as mp def square(n): return n*n if __name__ == '__main__': # create a pool of 4 worker processes with mp.Pool(processes=4) as pool: # list of numbers to calculate squares numbers = [1, 2, 3, 4, 5] # apply the square function asynchronously to each number results = [pool.apply_async(square, args=(n,)) for n in numbers] # get the result of each execution squares = [result.get() for result in results] print(squares)
[1, 4, 9, 16, 25]
import multiprocessing as mp import time def slow_square(n): time.sleep(2) # simulate a slow calculation return n*n if __name__ == '__main__': # create a pool of 4 worker processes with mp.Pool(processes=4) as pool: # list of numbers to calculate squares numbers = [1, 2, 3, 4, 5] # apply the slow_square function asynchronously to each number results = [pool.apply_async(slow_square, args=(n,)) for n in numbers] # print a message while waiting for results print("Waiting for results...") # get the result of each execution squares = [result.get() for result in results] print(squares)
Waiting for results... [1, 4, 9, 16, 25]In the above code, we created a pool of 4 worker processes using `mp.Pool(processes=4)`. Then we used this pool to apply the `slow_square` function to each number in the `numbers` list asynchronously using the `apply_async()` method. We stored the result of each execution in the `results` list. While waiting for results, we printed a message. Finally, we retrieved the result of each execution using the `get()` method on each `ApplyResult` object in `results`. The squares are stored in the `squares` list. Package Library: multiprocessing (built-in)