How to pass a function with more than one argument to python concurrent.futures.ProcessPoolExecutor.map()?

前端 未结 3 655
执笔经年
执笔经年 2021-01-04 02:16

I would like concurrent.futures.ProcessPoolExecutor.map() to call a function consisting of 2 or more arguments. In the example below, I have resorted to using a

3条回答
  •  甜味超标
    2021-01-04 02:37

    To answer your second question first, you are getting an exception because a lambda function like the one you're using is not picklable. Since Python uses the pickle protocol to serialize the data passed between the main process and the ProcessPoolExecutor's worker processes, this is a problem. It's not clear why you are using a lambda at all. The lambda you had takes two arguments, just like the original function. You could use _findmatch directly instead of the lambda and it should work.

    with cf.ProcessPoolExecutor(max_workers=workers) as executor:
        for n in executor.map(_findmatch, numberlist, ref):
            ...
    

    As for the first issue about passing the second, constant argument without creating a giant list, you could solve this in several ways. One approach might be to use itertools.repeat to create an iterable object that repeats the same value forever when iterated on.

    But a better approach would probably be to write an extra function that passes the constant argument for you. (Perhaps this is why you were trying to use a lambda function?) It should work if the function you use is accessible at the module's top-level namespace:

    def _helper(x):
        return _findmatch(x, 5)
    
    with cf.ProcessPoolExecutor(max_workers=workers) as executor:
        for n in executor.map(_helper, numberlist):
            ...
    

提交回复
热议问题