How to use multiprocessing pool.map with multiple arguments?

前端 未结 20 3832
-上瘾入骨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:39

    Here is another way to do it that IMHO is more simple and elegant than any of the other answers provided.

    This program has a function that takes two parameters, prints them out and also prints the sum:

    import multiprocessing
    
    def main():
    
        with multiprocessing.Pool(10) as pool:
            params = [ (2, 2), (3, 3), (4, 4) ]
            pool.starmap(printSum, params)
        # end with
    
    # end function
    
    def printSum(num1, num2):
        mySum = num1 + num2
        print('num1 = ' + str(num1) + ', num2 = ' + str(num2) + ', sum = ' + str(mySum))
    # end function
    
    if __name__ == '__main__':
        main()
    

    output is:

    num1 = 2, num2 = 2, sum = 4
    num1 = 3, num2 = 3, sum = 6
    num1 = 4, num2 = 4, sum = 8
    

    See the python docs for more info:

    https://docs.python.org/3/library/multiprocessing.html#module-multiprocessing.pool

    In particular be sure to check out the starmap function.

    I'm using Python 3.6, I'm not sure if this will work with older Python versions

    Why there is not a very straight-forward example like this in the docs, I'm not sure.

提交回复
热议问题