1. 程式人生 > >Python中為什麼要使用執行緒池?如何使用執行緒池?

Python中為什麼要使用執行緒池?如何使用執行緒池?

  系統處理任務時,需要為每個請求建立和銷燬物件.當有大量併發任務需要處理時,再使用傳統的多執行緒就會造成大量的資源建立銷燬導致伺服器效率的下降.這時候,執行緒池就派上用場了.執行緒池技術為執行緒建立、銷燬的開銷問題和系統資源不足問題提供了很好的解決方案.

 

from concurrent.futures import ThreadPoolExecutor
import os, time, random

def task(n):
    print('%s is runing' % os.getpid())
    time.sleep(random.randint(
1, 3)) return n ** 2 if __name__ == '__main__': executor = ThreadPoolExecutor(max_workers=3) executor.map(task, range(1, 7))