標籤:多個 方法 result rgs turn RoCE sed port col
內容:
concurrent庫簡介
Python 3.4+的concurrent庫用於多線程、並發編程,抽象層次高,使用方便。用得最多的是concurrent裡面的futures類,futures又有ThreadPoolExecutor和ProcessPoolExcutor兩個子類,前者用於多線程,後者用於多進程。
ThreadPoolExecutor.map()
ThreadPoolExcecutor類使用見下面代碼:
from concurrent import futuresimport timedef f(x): return x*(8-x)def test_func(n): print(f"{n} starts!") for i in range(n): time.sleep(0.5) return f"n = {n} completed!"def test(max_workers=4): with futures.ThreadPoolExecutor(max_workers) as executor: list1 = [ f(x) for x in range(1, max_workers+1)] # it is a iterator of results. it = executor.map(test_func, list1) print(it) for x in it: print(x)if __name__ == "__main__": m_workers = 6 test(m_workers)
Example
解釋:上面的例子中,對futures.ThreadPoolExecutor(也就是executor)調用map方法,這個map同內建的map用法一樣,第一個參數為只接受一個參數的函數,後一個為可迭代對象。不同的是,這個map方法會把對函數的調用映射到到多個線程中。並返回一個future的迭代器。
其中,f(x)是我特地構造的非單調函數,它返回一個值,決定了test_func()的睡眠時間,也就決定了線程執行完成的先後。
以下是上面例子的結果:
7 starts!12 starts!15 starts!16 starts!15 starts!12 starts!<generator object Executor.map.<locals>.result_iterator at 0x000002093367AA98>n = 7 completed!n = 12 completed!n = 15 completed!n = 16 completed!n = 15 completed!n = 12 completed!
Result1
上面反映出迭代器it是依照線程啟動的順序來迭代結果的,而非線程完成的先後順序。it中的元素是各個線程(函數)返回的結果。在實際的運行過程中,it是逐漸等待線程完成(n = 7 - 16),然後幾乎是同時把剩下的結果都列印出來。這說明前面(n = 7 ~ 16)的過程是阻塞的,而後面部分的線程已經全部執行完畢,沒有阻塞。
那麼當len(list1) > max_workers的時候呢?稍微修改程式:list1 = [ f(x) for x in range(1, max_workers+10)。程式執行結果如下:
7 starts!12 starts!15 starts!16 starts!15 starts!12 starts!<generator object Executor.map.<locals>.result_iterator at 0x0000029134D25A40> # print(it)7 starts!n = 7 completed! # 開始列印結果了,然而還有線程剛開始0 starts!n = 12 completed! # 阻塞-9 starts!-20 starts!-33 starts!-48 starts!-65 starts!-84 starts!-105 starts!n = 15 completed! n = 16 completed!n = 15 completed!n = 12 completed!n = 7 completed!n = 0 completed!n = -9 completed!n = -20 completed!n = -33 completed!n = -48 completed!n = -65 completed!n = -84 completed!n = -105 completed!
Result2
那麼這個修改後的Python代碼執行過程又是如何呢?(未完)
ThreadPoolExecutor.submit()和futures.as_completed()
.submit(func, *args)接受一個參數,*args的內容作為這個函數的參數,返回一個future對象。
futures.as_completed()返回一個迭代器,跟上嗎.map()不同,這個迭代器的迭代順序依照future返回(線程結束)的順序。代碼如下:
def test_2(max_workers=4): with futures.ThreadPoolExecutor(max_workers) as executor: list1 = [f(x) for x in range(1, max_workers+1)] it_ls = [] for x in list1: future = executor.submit(test_func, x) # 返回一個future it_ls.append(future) done_iter = futures.as_completed(it_ls) # as_completed()返回迭代器 print(done_iter) for x in done_iter: # x是future對象 print(x.result())
.submit() 和 .as_completed()
程式執行結果如下:
7 starts!12 starts!15 starts!16 starts!15 starts!12 starts!<generator object as_completed at 0x0000028AD6B79990>n = 7 completed!n = 12 completed!n = 12 completed!n = 15 completed!n = 15 completed!n = 16 completed!
Result_3
Python concurrent庫簡單用法