Search code examples
pythonparallel-processingmultiprocessingpython-multiprocessing

Parallel execution of a list of functions


So using the multiprocess module it is easy to run a function in parallel with different arguments like this:

from multiprocessing import Pool

def f(x):
    return x**2


p = Pool(2)
print(p.map(f, [1, 2]))

But I'm interested in executing a list of functions on the same argument. Suppose I have the following two functions:

def f(x):
    return x**2


def g(x):
    return x**3 + 2

How can I execute them in parallel for the same argument (e.g. x=1)?


Solution

  • You can use Pool.apply_async() for that. You bundle up tasks in the form of (function, argument_tuple) and feed every task to apply_async().

    from multiprocessing import Pool
    from itertools import repeat
    
    
    def f(x):
        for _ in range(int(50e6)): # dummy computation
            pass
        return x ** 2
    
    
    def g(x):
        for _ in range(int(50e6)): # dummy computation
            pass
        return x ** 3
    
    
    def parallelize(n_workers, functions, arguments):
        # if you need this multiple times, instantiate the pool outside and
        # pass it in as dependency to spare recreation all over again
        with Pool(n_workers) as pool:
            tasks = zip(functions, repeat(arguments))
            futures = [pool.apply_async(*t) for t in tasks]
            results = [fut.get() for fut in futures]
        return results
    
    
    if __name__ == '__main__':
    
        N_WORKERS = 2
    
        functions = f, g
        results = parallelize(N_WORKERS, functions, arguments=(10,))
        print(results)
    

    Example Output:

    [100, 1000]
    
    Process finished with exit code 0