如何将常量值(列表)传递给concurrent.futures.Executor.map?

问题描述 投票:0回答:1

无法回答我的确切用例的相关问题:

向concurrent.futures.Executor.map传递多个参数?

我有一个带有 2 个参数的函数。第二个参数是一个列表,在我的例子中,对于所有对

executor.map
的调用都是常量。

a = [1,2,3] # values to map and pass as single value
b = ["constant", "values"]
for result in executor.map(f, a, b): # how to pass always all values of b to f?
    # do stuff

我不依赖并发,如果这使得这成为可能或更容易的话,我也可以使用多处理。

python concurrent.futures
1个回答
0
投票

这是一个如何使用 functools 中的 partial 来实现此目的的示例:

from functools import partial
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor

USE_THREADS = False

def process(a, b):
    print(a)
    print(b)

def main():
    v = [1, 2, 3]
    c = ["constant", "values"]
    with (ThreadPoolExecutor if USE_THREADS else ProcessPoolExecutor)() as executor:
        executor.map(partial(process, c), v)

if __name__ == '__main__':
    main()

如果您想使用多线程,请将 USE_THREADS 设置为 True,或者将 USE_THREADS 设置为 False 进行多处理

输出:

['constant', 'values']
1
['constant', 'values']
2
['constant', 'values']
3
© www.soinside.com 2019 - 2024. All rights reserved.