![](/img/trans.png)
[英]How to handle data returned from thread functions in main function in Python
[英]How to thread a function in python that has two returned values
我有一個python函數,要求用戶輸入數據數組; 此時,該函數將對數據進行處理,並生成兩個數組,這些數組將返回到主程序。 在這個問題中,我包括一個大大簡化的示例,希望從中可以尋求一些建議或幫助。 我創建了一個名為“ Test_Function”的函數,該函數要求程序員提供一個名為“ Array”的數據數組,在這種情況下,該數組的長度為5000。該函數對數據起作用並生成兩組名為“ Result1”的數組,並且“ Result2”作為變量“ Res1”和“ Res2”在主程序中返回給用戶。 我想對函數進行線程處理,以使函數“ Test_Function”起作用,以便一個線程將在輸入數組的一半上工作,另一線程將在另一半上工作,然后在兩個輸出數組的主程序中將它們組合在一起“ Result1”和“ Result2” /“ Res1”和“ Res2”。 我描述了一種情況,其中我會產生兩個線程,但我想使其足夠通用,以便它可以運行用戶定義數量的線程。 我該如何使用線程功能?
import numpy as np
def Test_Function(Array):
Result1 = Array*np.pi*(1-Array)
Result2 = Array+478.5 + (1/Array)
return(np.array(Result1,dtype=float), np.array(Result2,dtype=float))
#---------------------------------------------------------------------------
if __name__ == "__main__":
Dependent_Array = np.linspace(1.0,5000.0,num=5000)
Res1, Res2 = Test_Function(Dependent_Array)
# eof
您可以使用ThreadPool來分配異步任務:
import numpy as np
from multiprocessing.pool import ThreadPool
def sub1(Array):
return Array * np.pi * (1-Array)
def sub2(Array):
return Array + 478.5 + (1/Array)
def Test_Function(Array):
pool = ThreadPool(processes=2)
res1 = pool.apply_async(sub1, (Array,))
res2 = pool.apply_async(sub2, (Array,))
return (np.array(res1.get(),dtype=float), np.array(res2.get(),dtype=float))
if __name__ == "__main__":
Dependent_Array = np.linspace(1.0,5000.0,num=5000)
Res1, Res2 = Test_Function(Dependent_Array)
這個模塊的文檔不是很好,但是,基本上,它創建了一個工作池,您可以向其分配子例程來執行。 apply_async
創建的結果對象的方法get()
僅在相應線程完成其操作apply_async
返回結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.