介绍:app
concurrent.futures模块提供了高度封装的异步调用接口异步
ThreadPoolExecutor:线程池,提供异步调用
ProcessPoolExecutor:进程池,提供异步调用ide
基本方法:
submit(fn,*args,**kwargs) 异步提交任务函数
map(func,*iterables,timeout=NOne,chunksize=1)渠道for循环submit的操做spa
shutdown(wait=True)至关于进程池的pool.close()+pool.join()操做线程
wait = True 等待池内全部任务执行完毕回收资源后才继续code
wait = False 当即返回,并不会等待池内的任务执行完毕blog
但无论wait参数为什么值,整个程序都会等到全部任务执行完毕接口
submit和map必须在shutdown以前进程
result(timeout=None)取得结果 至关于ret.get() 和ret.result()
add_done_callback(fn)回调函数 callback = fn
如何利用concurrent.futures模块开启线程池:
import time from threading import currentThread from concurrent.futures import ThreadPoolExecutor # 将ThreadPoolExecutor改为ProcessPoolExecutor就开启了多进程 def func(i): time.sleep(1) print('子线程',i,currentThread().ident) # 打印线程id
return i**2
tp = ThreadPoolExecutor(5) # 开启一个线程池里边有5个线程 for i in range(20): # 二十个任务 ret_l = [] # 弄个空列表准备装ret ret = tp.submit(func,i) # 用ret接收一下返回值 ret_l.append(ret) # 将ret放到ret_l中 for ret in ret_l: # 遍历ret_l print(ret.result()) # 打印返回值,注意这里的接口是result() tp.shutdown() # 关闭线程池
使用map开启线程池:
import time from threading import currentThread from concurrent.futures import ThreadPoolExecutor def func(i): time.sleep(1) print('子线程',i,currentThread().ident) tp = ThreadPoolExecutor(5) tp.map(func,range(20))
回调函数:
import time from threading import currentThread from concurrent.futures import ThreadPoolExecutor # 将ThreadPoolExecutor改为ProcessPoolExecutor就开启了多进程 def func(i): time.sleep(1) print('子线程',i,currentThread().ident) # 打印线程id return i ** 2 def call_back(ret): # 回调函数 print(ret.result()) # 打印返回值 tp = ThreadPoolExecutor(5) # 开启一个线程池里边有5个线程 for i in range(20): # 二十个任务 ret = tp.submit(func,i).add_done_callback(call_back) # 用ret接收一下返回值 tp.shutdown() # 关闭线程池