首页 > 解决方案 > 线程没有与 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

难道我做错了什么?我阅读了其他一些较旧的帖子,但我无法获得任何信息。非常感谢您的帮助!

标签: pythonmachine-learningconcurrencypython-multithreading

解决方案


由于GIL,Python 线程不会并行运行(至少在 CPython 实现中)。使用进程和ProcessPoolExecutor真正具有并行性

with concurrent.futures.ProcessPoolExecutor() as executor:
    ...

推荐阅读