python - 如何访问传递给 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
?
解决方案
如果不出意外,您可以枚举结果并将结果与原始输入相匹配。
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)
)
推荐阅读
- python - 有没有办法在 python 中加快这种平滑操作?
- angular - ag-grid 角度访问 selectionController.getLastSelectedNode()
- impala - 有没有办法以色调查看表和列的列表
- python - 如果特定索引为空,如何将某些项目附加到新列表
- function - 添加到 []interface{} 的对象。现在需要获取对象并调用对象各自的 Display() fn
- node.js - 如何列出模块的所有依赖项而不安装它们
- html - 选择表单选项时将活动类添加到轮播项目
- reactjs - React Hook useMemo 有一个不必要的依赖:'match'
- java - Spring - 无法执行 CommandLineRunner:@Bean
- jquery - Bootstrap 4 Accordian 滚动打开内容?