python - 线程没有与 ThreadPoolExecutor 并行执行 python
问题描述
我是 python 线程的新手,我正在试验这个:当我在线程中运行某些东西时(每当我打印输出时),它似乎永远不会并行运行。此外,我的函数与使用库 concurrent.futures (ThreadPoolExecutor) 之前的时间相同。我必须计算数据集上某些属性的增益(我不能使用库)。由于我有大约 1024 个属性并且该函数需要大约一分钟才能执行(并且我必须在 for 迭代中使用它)我决定将数组拆分attributes
为 10(仅作为示例)并单独运行gain(attribute)
单独的函数每个子数组。所以我做了以下事情(避免一些额外的不必要的代码):
def calculate_gains(self):
splited_attributes = np.array_split(self.attributes, 10)
result = {}
for atts in splited_attributes:
with concurrent.futures.ThreadPoolExecutor() as executor:
future = executor.submit(self.calculate_gains_helper, atts)
return_value = future.result()
self.gains = {**self.gains, **return_value}
这是calculate_gains_helper:
def calculate_gains_helper(self, attributes):
inter_result = {}
for attribute in attributes:
inter_result[attribute] = self.gain(attribute)
return inter_result
难道我做错了什么?我阅读了其他一些较旧的帖子,但我无法获得任何信息。非常感谢您的帮助!
解决方案
由于GIL,Python 线程不会并行运行(至少在 CPython 实现中)。使用进程和ProcessPoolExecutor真正具有并行性
with concurrent.futures.ProcessPoolExecutor() as executor:
...
推荐阅读
- neo4j - Neo4j WHERE 导致重复?
- java - 如何从 XML 文件 (JRC) Java 设置 Crystal Report 数据源
- c# - 根据数据改变背景
- java - 无法解析方法“writeJson(java.lang.String,javax.servlet.http.HttpServletResponse)”
- r - 在 R 中设置颜色条限制
- python - 当python没有返回时,如何访问另一个函数中的值?
- ios - SwiftUI:NavigationView/NavigationLink:启动并推送目的地?
- kentico - Kentico 13 上缺少字典
- javascript - 如何从 document.write 内的脚本访问 document.body
- mysql - 将数据帧转换为 SQL 时出错 - Pandas