Python程序中的线程操作-concurrent模块

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 = ProcessPoolExecutor(4)
    fu_list = []
    for i in range(10):
        future = pool.submit(task,i)
        print(future.result())  # 拿不到值会阻塞在这里。
        fu_list.append(future)
 
    pool.shutdown(wait=True)  # 等待池内所有任务执行完毕
    print("*"*20)
 
    for i in fu_list:
        print(i.result())# 拿不到值会阻塞在这里。
Outputs
macname@MacdeMacBook-Pro py % python3 cccccc.py
MainThread 在运行 任务0
ForkProcess-1 在运行 任务0
0
MainThread 在运行 任务1
ForkProcess-2 在运行 任务1
1
MainThread 在运行 任务2
ForkProcess-3 在运行 任务2
4
MainThread 在运行 任务3
ForkProcess-4 在运行 任务3
9
MainThread 在运行 任务4
ForkProcess-1 在运行 任务4
16
MainThread 在运行 任务5
ForkProcess-2 在运行 任务5
25
MainThread 在运行 任务6
ForkProcess-3 在运行 任务6
36
MainThread 在运行 任务7
ForkProcess-4 在运行 任务7
49
MainThread 在运行 任务8
ForkProcess-1 在运行 任务8
64
MainThread 在运行 任务9
ForkProcess-2 在运行 任务9
81
********************
0
1
4
9
16
25
36
49
64
81
macname@MacdeMacBook-Pro py %

 

 
 
 
 
 
 
 
 
 
 

posted @ 2020-12-26 18:07  anobscureretreat  阅读(93)  评论(0编辑  收藏  举报