How to use multiprocessing pool.map with multiple arguments?

前端 未结 20 3500
-上瘾入骨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条回答
  •  Happy的楠姐
    2020-11-21 11:55

    Another simple alternative is to wrap your function parameters in a tuple and then wrap the parameters that should be passed in tuples as well. This is perhaps not ideal when dealing with large pieces of data. I believe it would make copies for each tuple.

    from multiprocessing import Pool
    
    def f((a,b,c,d)):
        print a,b,c,d
        return a + b + c +d
    
    if __name__ == '__main__':
        p = Pool(10)
        data = [(i+0,i+1,i+2,i+3) for i in xrange(10)]
        print(p.map(f, data))
        p.close()
        p.join()
    

    Gives the output in some random order:

    0 1 2 3
    1 2 3 4
    2 3 4 5
    3 4 5 6
    4 5 6 7
    5 6 7 8
    7 8 9 10
    6 7 8 9
    8 9 10 11
    9 10 11 12
    [6, 10, 14, 18, 22, 26, 30, 34, 38, 42]
    

提交回复
热议问题