JabberJabber
JabberJabber

Reputation: 383

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.

Upvotes: 1

Views: 2198

Answers (2)

Cihan
Cihan

Reputation: 2307

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)   

Upvotes: 2

Adam.Er8
Adam.Er8

Reputation: 13413

you need to create a wrapper function that accepts a single arg (a tuple) and passes it using * to your add function.

NOTICE: you also want to iterate the results to actually access them:

import concurrent.futures


def add(x, y):
    return x + y


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

res = []
with concurrent.futures.ThreadPoolExecutor(1) as executor:
    for r in executor.map(lambda t: add(*t), numbers):
        res.append(r)

print(res)

Upvotes: 1

Related Questions