Search code examples
pythonpython-3.xconcurrent.futures

Using ThreadPoolExecutor's Map Passing Multiple Values


I am trying to figure out how to use the ThreadPoolExecutor.map() in the current.futures library. I am using Python 3.6.

Here is the code shown below

import concurrent.futures
def add(x,y):
    return x+y

with concurrent.futures.ThreadPoolExecutor(1) as executor:
    res = executor.map(add, *(1,2)) # Fails 

My issue is that when I pass my parameters, I get the following error:

builtins.TypeError: zip argument #1 must support iteration

The example on the Python docs only shows using one variable as input, but I would like to use N variables for the map function. How do I do this?

I'm really scratching my head on this one, and would appreciate if anyone could point me to how I need to format my input parameters.

I would like to be able to do something like this:

import concurrent.futures
def add(x,y):
    return x+y

numbers = [
(1,2), (2,3), (3,10)
]

with concurrent.futures.ThreadPoolExecutor(1) as executor:
    res = executor.map(add, *numbers) 

Please advise me on how to format the parameter inputs.


Solution

  • You can use a lambda to do it as follows:

    import concurrent.futures
    def add(x,y):
        return x+y
    numbers = [(1,2), (2,3), (3,10)]
    with concurrent.futures.ThreadPoolExecutor(1) as executor:
        res = executor.map(lambda args : add(*args), numbers)