How to use multiprocessing pool.map with multiple arguments?

前端 未结 20 3442
-上瘾入骨i
-上瘾入骨i 2020-11-21 11:24

In the Python multiprocessing library, is there a variant of pool.map which supports multiple arguments?

text = "test"
def         


        
20条回答
  •  离开以前
    2020-11-21 11:48

    This is an example of the routine I use to pass multiple arguments to a one-argument function used in a pool.imap fork:

    from multiprocessing import Pool
    
    # Wrapper of the function to map:
    class makefun:
        def __init__(self, var2):
            self.var2 = var2
        def fun(self, i):
            var2 = self.var2
            return var1[i] + var2
    
    # Couple of variables for the example:
    var1 = [1, 2, 3, 5, 6, 7, 8]
    var2 = [9, 10, 11, 12]
    
    # Open the pool:
    pool = Pool(processes=2)
    
    # Wrapper loop
    for j in range(len(var2)):
        # Obtain the function to map
        pool_fun = makefun(var2[j]).fun
    
        # Fork loop
        for i, value in enumerate(pool.imap(pool_fun, range(len(var1))), 0):
            print(var1[i], '+' ,var2[j], '=', value)
    
    # Close the pool
    pool.close()
    

提交回复
热议问题