池模塊 -進程池 -線程池

池模塊

線程池concurrent.futures.ThreadPoolExecutor

from concurrent.futures import ThreadPoolExecutor
    from time import sleep
    
    tpool = ThreadPoolExecutor(max_workers=5)   #設置線程最大數量
    
    def func(i):
        sleep(1)
        print(i)
    
    for i in range(20):
        tpool.submit(func, i)
    tpool.shutdown()    #等待全部子線程運行結束
    print('主線程在這裏')
  • t.result() 獲取函數的返回值

進程池concurrent.futures.ProcessPoolExecutor

from concurrent.futures import ProcessPoolExecutor
        from time import sleep
        tpool = ProcessPoolExecutor(max_workers=5)  #這是最大進程數
        
        def func(i):
            sleep(1)
            print(i)
        
        for i in range(20):
            tpool.submit(func, i)
        tpool.shutdown()    #等待全部子進程運行結束
        print('主線程在這裏')
- `t.result()   `   獲取函數的返回值
相關文章
相關標籤/搜索