介紹:app
concurrent.futures模塊提供了高度封裝的異步調用接口異步
ThreadPoolExecutor:線程池,提供異步調用
ProcessPoolExecutor:進程池,提供異步調用ide
基本方法:
submit(fn,*args,**kwargs) 異步提交任務函數
map(func,*iterables,timeout=NOne,chunksize=1)渠道for循環submit的操做spa
shutdown(wait=True)至關於進程池的pool.close()+pool.join()操做線程
wait = True 等待池內全部任務執行完畢回收資源後才繼續code
wait = False 當即返回,並不會等待池內的任務執行完畢blog
但無論wait參數爲什麼值,整個程序都會等到全部任務執行完畢接口
submit和map必須在shutdown以前進程
result(timeout=None)取得結果 至關於ret.get() 和ret.result()
add_done_callback(fn)回調函數 callback = fn
如何利用concurrent.futures模塊開啓線程池:
import time from threading import currentThread from concurrent.futures import ThreadPoolExecutor # 將ThreadPoolExecutor改爲ProcessPoolExecutor就開啓了多進程 def func(i): time.sleep(1) print('子線程',i,currentThread().ident) # 打印線程id
return i**2
tp = ThreadPoolExecutor(5) # 開啓一個線程池裏邊有5個線程 for i in range(20): # 二十個任務 ret_l = [] # 弄個空列表準備裝ret ret = tp.submit(func,i) # 用ret接收一下返回值 ret_l.append(ret) # 將ret放到ret_l中 for ret in ret_l: # 遍歷ret_l print(ret.result()) # 打印返回值,注意這裏的接口是result() tp.shutdown() # 關閉線程池
使用map開啓線程池:
import time from threading import currentThread from concurrent.futures import ThreadPoolExecutor def func(i): time.sleep(1) print('子線程',i,currentThread().ident) tp = ThreadPoolExecutor(5) tp.map(func,range(20))
回調函數:
import time from threading import currentThread from concurrent.futures import ThreadPoolExecutor # 將ThreadPoolExecutor改爲ProcessPoolExecutor就開啓了多進程 def func(i): time.sleep(1) print('子線程',i,currentThread().ident) # 打印線程id return i ** 2 def call_back(ret): # 回調函數 print(ret.result()) # 打印返回值 tp = ThreadPoolExecutor(5) # 開啓一個線程池裏邊有5個線程 for i in range(20): # 二十個任務 ret = tp.submit(func,i).add_done_callback(call_back) # 用ret接收一下返回值 tp.shutdown() # 關閉線程池