python并发编程-线程池

from concurrent.futures import ThreadPoolExecutor
import time

def func(n):
    time.sleep(2)
    print(n)
    return n*n
t_pool = ThreadPoolExecutor(max_workers=20) #max_workers一般不超过CPU*5,创建线程池
t_lst = []
for i in range(20):
    t = t_pool.submit(func,i) #提交多线程认为
    t_lst.append(t)
t_pool.shutdown() #可以完成close和join的操作
print('主线程')
for t in t_lst:print('****',t.result())

线程池callback

from concurrent.futures import ThreadPoolExecutor
import time

def func(n):
    time.sleep(2)
    print(n)
    return n*n

def call_back(m):
    print('结果是%s'%m.result())
t_pool = ThreadPoolExecutor(max_workers=20) #max_workers一般不超过CPU*5,创建线程池
for i in range(20):
    t = t_pool.submit(func,i).add_done_callback(call_back)
# t_pool.map(func,range(20)) #t_pool.map是没有返回值的
posted @ 2018-09-27 14:00  空林~~清风~~~  阅读(177)  评论(0编辑  收藏  举报