簡體   English   中英

線程未與 ThreadPoolExecutor 並行執行 python

[英]Threads is not executing in parallel python with ThreadPoolExecutor

我是 python 線程的新手,我正在試驗這個:當我在線程中運行某些東西時(每當我打印輸出時),它似乎永遠不會並行運行。 此外,我的函數與使用庫 concurrent.futures (ThreadPoolExecutor) 之前的時間相同。 我必須計算數據集上某些屬性的增益(我不能使用庫)。 由於我有大約 1024 個屬性,並且 function 需要大約一分鍾來執行(並且我必須在 for 迭代中使用它)我決定將attributes數組分成 10 個(僅作為示例)並運行單獨的 function 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:
    ...

您提交然后依次等待每個工作項,因此所有線程都會減慢一切。 我不能保證這會大大加快速度,因為您仍在處理 python GIL,它使 python 級別的東西無法並行工作,但這里有。

我創建了一個線程池,並將所有可能的東西都推送到了 worker 中,包括self.attributes的切片。

def calculate_gains(self):
    with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
        result_list = executor.map(self.calculate_gains_helper,
            ((i, i+10) for i in range(0, len(self.attributes), 10)))
    for return_value in result_list:
        self.gains = {**self.gains, **return_value}

def calculate_gains_helper(self, start_end):
    start, end = start_end
    inter_result = {}
    for attribute in self.attributes[start:end]:
        inter_result[attribute] = self.gain(attribute)
    return inter_result

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM