ThreadPoolExecutor包含两个列表中的所有参数

时间:2018-01-14 01:13:23

标签: multithreading python-3.x

我有两个清单:

a = [1, 2, 3, 4]
b = [9, 8, 7, 6]

我希望将这两个列表的每个组合作为参数传递给函数I'多线程:

def test(hello, world):
    return hello + world

with ThreadPoolExecutor(max_workers=10) as executor:
    future_to_stuff = { executor.submit(self._http_check_port, hello, world): ### }
    for future in as_completed(future_to_port):
        ...

我试图找出如何解开"解包"我的两个列表都将ab中的每个值组合作为参数发送给函数。

1 个答案:

答案 0 :(得分:2)

我通常使用以下列表理解。

future_to_stuff = [executor.submit(test, hello, world) 
                   for hello, world in zip(a, b)]

这是修改后的代码。

from concurrent.futures import ThreadPoolExecutor, as_completed

def test(hello, world):
    return hello + world

def main(a, b):
    with ThreadPoolExecutor(max_workers=10) as executor:
        future_to_stuff = [executor.submit(test, hello, world) 
                           for hello, world in zip(a, b)]
        for future in as_completed(future_to_stuff):
            print(future.result())

if __name__ == '__main__':
    a = [1, 2, 3, 4]
    b = [9, 8, 7, 6]
    main(a, b)

另一种方法是使用.map方法而不是.submit

from concurrent.futures import ThreadPoolExecutor, as_completed

def test(hello, world):
    return hello + world

def main(a, b):
    with ThreadPoolExecutor(max_workers=10) as executor:
        results = executor.map(test, a, b)
        for result in results:
            print(result)

if __name__ == '__main__':
    a = [1, 2, 3, 4]
    b = [9, 8, 7, 6]
    main(a, b)