如何访问传递给Python线程的函数args?
我使用以下代码(为了保密而简化)在python中运行多个线程如何访问传递给Python线程的函数args?,python,multithreading,threadpoolexecutor,Python,Multithreading,Threadpoolexecutor,我使用以下代码(为了保密而简化)在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 是否有一种方法可以访问每个线程用于获取结果的参数,而无需
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
是否有一种方法可以访问每个线程用于获取
结果的参数,而无需my_函数
将这些参数作为result
的一部分返回?如果没有其他方法,您可以枚举结果并将结果与原始输入匹配
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
的文档提供了一个示例,表明返回结果的顺序与使用参数的顺序相同。我假设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)
)谢谢你,切普纳。返回结果的顺序与实际使用的参数相同。我没有尝试过其他解决方案,因为这些信息已经解决了手头的问题。