1、新模块
from concurrent.futures import ThreadPoolExecutor from concurrent.futures import ProcessPoolExecutor
2、方法
""" 线程数量一般是cpu个数*5 submit(函数名, 参数) map(函数名, 可迭代对象) obj.shutdown() 相当于obj.close()和obj.join() obj.result() 获取返回值 and_done_callback(函数),回调函数 done() 查看某个线程是否完成 """
3、示例
import time from concurrent.futures import ThreadPoolExecutor def test1(n): time.sleep(0.5) print(n) return pow(n, 2) t_pool = ThreadPoolExecutor(5) # 线程池中线程的数量 t_li = [] for i in range(12): ret = t_pool.submit(test1, i) # 异步 # print(ret.result()) t_li.append(ret) t_pool.shutdown() # 相当于close()和join()方法 print('adaf') for t in t_li: print('***', t.result())
import time from concurrent.futures import ThreadPoolExecutor def test1(n): time.sleep(0.5) # print(n) return pow(n, 2) def test2(m): print(m.result()) t_pool = ThreadPoolExecutor(5) # 线程池中线程的数量 t_li = [] for i in range(12): t_pool.submit(test1, i).add_done_callback(test2) # 回调函数
import time from concurrent.futures import ThreadPoolExecutor def test1(n): time.sleep(0.5) print(n) return pow(n, 2) t_pool = ThreadPoolExecutor(5) # 线程池中线程的数量 t_pool.map(test1, range(6)) # map()异步