原文來自開源中國
python標準庫提供線程和多處理模塊來編寫相應的多線程/多進程代碼,但當項目達到一定規模時,頻繁地創建/銷毀進程或線程是非常消耗資源的,此時我們必須編寫自己的線程池/進程池來交換時間空間。但是從Python3.2開始,標準庫為我們提供了并發的。Futures模塊,它提供兩個類:ThreadPool Executor和ProcessPool Executor。它實現線程和多處理的進一步抽象,并為編寫線程池/進程池提供直接支持。
concurrent.futures模塊的基礎是Exectuor,Executor是一個抽象類,它不能被直接使用。但是它提供的兩個子類ThreadPoolExecutor和ProcessPoolExecutor卻是非常有用,顧名思義兩者分別被用來創建線程池和進程池的代碼。我們可以將相應的tasks直接放入線程池/進程池,不需要維護Queue來操心死鎖的問題,線程池/進程池會自動幫我們調度。
我們先通過下面這段代碼來了解一下線程池的概念
# example1.pyfrom concurrent.futures import ThreadPoolExecutorimport timedef return_future_result(message): time.sleep(2) return message pool = ThreadPoolExecutor(max_workers=2) # 創建一個最大可容納2個task的線程池future1 = pool.submit(return_future_result, ("hello")) # 往線程池里面加入一個taskfuture2 = pool.submit(return_future_result, ("world")) # 往線程池里面加入一個taskprint(future1.done()) # 判斷task1是否結束time.sleep(3) print(future2.done()) # 判斷task2是否結束print(future1.result()) # 查看task1返回的結果print(future2.result()) # 查看task2返回的結果
讓我們根據操作結果進行分析。我們使用submit方法將任務添加到線程池,submit返回一個將來的對象,這可以簡單地理解為將來要完成的操作。在第一份印刷聲明中,很明顯我們的未來1由于時間的原因沒有完成。睡眠(2),因為我們使用時間掛起了主線程。sleep(3),所以到第二個print語句時,線程池中的所有任務都已完成。
ziwenxie :: ~ ? python example1.pyFalseTruehello world# 在上述程序執行的過程中,通過ps命令我們可以看到三個線程同時在后臺運行ziwenxie :: ~ ? ps -eLf | grep python ziwenxie 8361 7557 8361 3 3 19:45 pts/0 00:00:00 python example1.py ziwenxie 8361 7557 8362 0 3 19:45 pts/0 00:00:00 python example1.py ziwenxie 8361 7557 8363 0 3 19:45 pts/0 00:00:00 python example1.py
上面的代碼我們也可以改寫為進程池形式,api和線程池如出一轍,我就不羅嗦了。
# example2.pyfrom concurrent.futures import ProcessPoolExecutorimport timedef return_future_result(message): time.sleep(2) return message pool = ProcessPoolExecutor(max_workers=2) future1 = pool.submit(return_future_result, ("hello")) future2 = pool.submit(return_future_result, ("world")) print(future1.done()) time.sleep(3) print(future2.done()) print(future1.result()) print(future2.result())
下面是運行結果
ziwenxie :: ~ ? python example2.pyFalseTruehello world ziwenxie :: ~ ? ps -eLf | grep python ziwenxie 8560 7557 8560 3 3 19:53 pts/0 00:00:00 python example2.py ziwenxie 8560 7557 8563 0 3 19:53 pts/0 00:00:00 python example2.py ziwenxie 8560 7557 8564 0 3 19:53 pts/0 00:00:00 python example2.py ziwenxie 8561 8560 8561 0 1 19:53 pts/0 00:00:00 python example2.py ziwenxie 8562 8560 8562 0 1 19:53 pts/0 00:00:00 python example2.py
除了submit,Exectuor還為我們提供了map方法,和內建的map用法類似,下面我們通過兩個例子來比較一下兩者的區別。
使用submit操作回顧
# example3.pyimport concurrent.futuresimport urllib.request URLS = ['http://httpbin.org', 'http://example.com/', 'https://api.github.com/']def load_url(url, timeout): with urllib.request.urlopen(url, timeout=timeout) as conn: return conn.read()# We can use a with statement to ensure threads are cleaned up promptlywith concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor: # Start the load operations and mark each future with its URL future_to_url = {executor.submit(load_url, url, 60): url for url in URLS} for future in concurrent.futures.as_completed(future_to_url): url = future_to_url[future] try: data = future.result() except Exception as exc: print('%r generated an exception: %s' % (url, exc)) else: print('%r page is %d bytes' % (url, len(data)))
從運行結果可以看出,as_completed不是按照URLS列表元素的順序返回的。
ziwenxie :: ~ ? python example3.py'http://example.com/' page is 1270 byte'https://api.github.com/' page is 2039 bytes'http://httpbin.org' page is 12150 bytes
使用map
# example4.pyimport concurrent.futuresimport urllib.request URLS = ['http://httpbin.org', 'http://example.com/', 'https://api.github.com/']def load_url(url): with urllib.request.urlopen(url, timeout=60) as conn: return conn.read()# We can use a with statement to ensure threads are cleaned up promptlywith concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor: for url, data in zip(URLS, executor.map(load_url, URLS)): print('%r page is %d bytes' % (url, len(data)))
從運行結果可以看出,map是按照URLS列表元素的順序返回的,并且寫出的代碼更加簡潔直觀,我們可以根據具體的需求任選一種。
ziwenxie :: ~ ? python example4.py'http://httpbin.org' page is 12150 bytes'http://example.com/' page is 1270 bytes'https://api.github.com/' page is 2039 bytes
第三種選擇wait
wait方法接會返回一個tuple(元組),tuple中包含兩個set(集合),一個是completed(已完成的)另外一個是uncompleted(未完成的)。使用wait方法的一個優勢就是獲得更大的自由度,它接收三個參數FIRST_COMPLETED, FIRST_EXCEPTION 和ALL_COMPLETE,默認設置為ALL_COMPLETED。
我們通過下面這個例子來看一下三個參數的區別
from concurrent.futures import ThreadPoolExecutor, wait, as_completedfrom time import sleepfrom random import randintdef return_after_random_secs(num): sleep(randint(1, 5)) return "Return of {}".format(num) pool = ThreadPoolExecutor(5) futures = []for x in range(5): futures.append(pool.submit(return_after_random_secs, x)) print(wait(futures))# print(wait(futures, timeout=None, return_when='FIRST_COMPLETED'))
如果采用默認的ALL_COMPLETED,程序會阻塞直到線程池里面的所有任務都完成。
ziwenxie :: ~ ? python example5.py DoneAndNotDoneFutures(done={<Future at 0x7f0b06c9bc88 state=finished returned str>,<Future at 0x7f0b06cbaa90 state=finished returned str>,<Future at 0x7f0b06373898 state=finished returned str>,<Future at 0x7f0b06352ba8 state=finished returned str>,<Future at 0x7f0b06373b00 state=finished returned str>}, not_done=set())
如果采用FIRST_COMPLETED參數,程序并不會等到線程池里面所有的任務都完成。
ziwenxie :: ~ ? python example5.py DoneAndNotDoneFutures(done={<Future at 0x7f84109edb00 state=finished returned str>,<Future at 0x7f840e2e9320 state=finished returned str>,<Future at 0x7f840f25ccc0 state=finished returned str>}, not_done={<Future at 0x7f840e2e9ba8 state=running>,<Future at 0x7f840e2e9940 state=running>})
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。