python 使用线程池,回调函数
对应示例代码,回调函数不会阻塞
import time from concurrent.futures import ThreadPoolExecutor def get(delay): print('delay {}s'.format(delay)) time.sleep(delay) # 延时 return {'delay': delay+5} # 返回结果 def parse(res): res = res.result() # !取到res结果 【回调函数】带参数需要这样 print('res is {}' .format (res['delay'])) if __name__ == '__main__': time_delay = [1,3,2] pool = ThreadPoolExecutor(len(time_delay)) for i in time_delay: pool.submit(get, i).add_done_callback(parse) # 【回调函数】执行完线程后,跟一个函数 print("hello")
通过以下结果可以发现,并没有阻塞主线程,只是当线程运行完成之后,就会调用parse。
输出结果:
delay 1s delay 3s delay 2s hello res is 6 res is 7 res is 8