1. 程式人生 > >Python3【模塊】concurrent.futures模塊,線程池進程池

Python3【模塊】concurrent.futures模塊,線程池進程池

tro containe them executor 進程池 自己的 from port clas

  Python標準庫為我們提供了threading和multiprocessing模塊編寫相應的多線程/多進程代碼,但是當項目達到一定的規模,頻繁創建/銷毀進程或者線程是非常消耗資源的,這個時候我們就要編寫自己的線程池/進程池,以空間換時間。但從Python3.2開始,標準庫為我們提供了concurrent.futures模塊,它提供了ThreadPoolExecutor和ProcessPoolExecutor兩個類,實現了對threading和multiprocessing的進一步抽象,對編寫線程池/進程池提供了直接的支持。 模塊:concurrent.futures模塊的ThreadPoolExecutor,ProcessPoolExecutor子類
簡單實例:
from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor
import time

def task(arg1,arg2):
    print(arg1,arg2)
    time.sleep(1)

# pool = ProcessPoolExecutor(10)
pool = ThreadPoolExecutor(10)

for i in range(100):
    pool.submit(task,i,i)

  

Python3【模塊】concurrent.futures模塊,線程池進程池