import multiprocessing def worker(x): return x*x if __name__ == '__main__': with multiprocessing.Pool(processes=4) as pool: result = pool.map(worker, range(10)) pool.close() # Close the pool to avoid additional tasks pool.join() print(result)
import multiprocessing import time def worker(x): time.sleep(1) # Emulate a long-running task return x*x if __name__ == '__main__': with multiprocessing.Pool(processes=4) as pool: tasks = range(10) results = [] for task in tasks: result = pool.apply_async(worker, args=(task,)) results.append(result) pool.close() # Close the pool to avoid additional tasks pool.join() output = [result.get() for result in results] print(output)In this example, we're creating a pool with four worker processes and using the `apply_async` method to execute the function `worker` on each element of the `range(10)` iterable. We then close the pool using the `close` method, wait for all tasks to complete using the `join` method, and retrieve the results from each task using the `get` method of each `AsyncResult` object.