python3 ThreadPoolExecutor

code
from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor
from threading import currentThread
from multiprocessing import current_process
import time,os
 
 
def task(i):
    print(f'{currentThread().name} 在运行 任务{i}')
    print(f'{current_process().name} 在运行 任务{i}')
    time.sleep(0.2)
    return i**2
 
 
if __name__ == '__main__':
    pool = ThreadPoolExecutor(4)
    fu_list = []
    for i in range(20):
        future = pool.submit(task,i)
        # print(future.result())  # 拿不到值会阻塞在这里。
        fu_list.append(future)
 
 
    pool.shutdown(wait=True)  # 等待池内所有任务执行完毕
    for i in fu_list:
        print(i.result())# 拿不到值会阻塞在这里。
outputs
macname@MacdeMacBook-Pro py % python3 cccccc.py
ThreadPoolExecutor-0_0 在运行 任务0
ThreadPoolExecutor-0_1 在运行 任务1
MainProcess 在运行 任务1
ThreadPoolExecutor-0_2 在运行 任务2
ThreadPoolExecutor-0_3 在运行 任务3
MainProcess 在运行 任务0
MainProcess 在运行 任务2
MainProcess 在运行 任务3
ThreadPoolExecutor-0_1 在运行 任务4
MainProcess 在运行 任务4
ThreadPoolExecutor-0_0 在运行 任务5
MainProcess 在运行 任务5
ThreadPoolExecutor-0_3 在运行 任务7
ThreadPoolExecutor-0_2 在运行 任务6
MainProcess 在运行 任务7
MainProcess 在运行 任务6
ThreadPoolExecutor-0_1 在运行 任务8
MainProcess 在运行 任务8
ThreadPoolExecutor-0_0 在运行 任务9
MainProcess 在运行 任务9
ThreadPoolExecutor-0_2 在运行 任务11
MainProcess 在运行 任务11
ThreadPoolExecutor-0_3 在运行 任务10
MainProcess 在运行 任务10
ThreadPoolExecutor-0_0 在运行 任务12
MainProcess 在运行 任务12
ThreadPoolExecutor-0_3 在运行 任务13
ThreadPoolExecutor-0_2 在运行 任务14
MainProcess 在运行 任务13
MainProcess 在运行 任务14
ThreadPoolExecutor-0_1 在运行 任务15
MainProcess 在运行 任务15
ThreadPoolExecutor-0_0 在运行 任务16
ThreadPoolExecutor-0_2 在运行 任务17
MainProcess 在运行 任务16
MainProcess 在运行 任务17
ThreadPoolExecutor-0_3 在运行 任务18
MainProcess 在运行 任务18
ThreadPoolExecutor-0_1 在运行 任务19
MainProcess 在运行 任务19
0
1
4
9
16
25
36
49
64
81
100
121
144
169
196
225
256
289
324
361
macname@MacdeMacBook-Pro py %

 

 
 
 
 
 
 
 
 
 

posted @ 2020-12-26 17:38  anobscureretreat  阅读(300)  评论(0编辑  收藏  举报