首页 > 解决方案 > 如何访问传递给 Python 线程的函数 args?

问题描述

我正在使用以下代码(为保密起见进行了简化)在 python 中运行多个线程。

pool = ThreadPoolExecutor(max_workers=3)
for result in pool.map(my_function, [1, 2, 3], ['a', 'b', 'c']):
    # do something with the result depending on which arguments the thread has used

有没有一种方法可以访问每个线程用来获取的参数,result而无需my_function将它们作为 的一部分返回result

标签: pythonmultithreadingthreadpoolexecutor

解决方案


如果不出意外,您可以枚举结果并将结果与​​原始输入相匹配。

arg1s = [1, 2, 3]
arg2s = ['a', 'b', 'c']

for i, result in enumerate(pool.map(my_function, arg1s, arg2s)):
    # If i == 1, then result == my_function(1, 'a')
    # If i == 2, then result == my_function(2, 'b')
    # etc
    ...

(文档ProcessPoolExecutor提供了一个示例,map这意味着结果的返回顺序与使用参数的顺序相同。我假设 也是如此ThreadPoolExecutor,因为map它继承自Executor。事实上,您可以编写一个更笨重的版本来遵守更接近那个例子:

for arg1, arg2, result in zip(arg1s, arg2s, pool.map(lambda x: my_function(*x), arg1s, arg2s)):
    # result == my_function(arg1, arg2)

)


推荐阅读