Parallel execution of a list of functions

后端 未结 2 1223
南方客
南方客 2021-01-25 06:37

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):
    ret         


        
2条回答
  •  灰色年华
    2021-01-25 07:18

    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
    

提交回复
热议问题