# 线程池
# 实例化线程池 ThreadPoolExcutor (推荐cpu_count*(n+1))
# 异步提交任务 submit / map
# 阻塞直到任务完成 shutdown
# 获取子线程的返回值 result
# 使用回调函数 add_done_callback
(1)基本用法:
from concurrent.futures import ThreadPoolExecutor def func(i): print("thread is start",i) print("thread is end ") if __name__ == "__main__": p = ThreadPoolExecutor(5) p.submit(func,1) #启动线程 p.shutdown() # 相当于join+close print("主线程")
执行结果:
thread is start 1 thread is end 主线程
(2)返回值 ( 通过对象.result()拿到结果 )
from concurrent.futures import ThreadPoolExecutor def func(i): print("thread %s start" % (i)) print("thread %s end" % (i)) return i * "*" tp = ThreadPoolExecutor(5) lst = [] for i in range(20): res = tp.submit(func,i) #返回值也是对象 lst.append(res) tp.shutdown() for res in lst: print(res.result())
执行结果:
thread 0 start thread 0 end thread 1 start thread 2 start thread 1 endthread 2 end thread 3 start thread 3 end thread 4 start thread 4 end thread 5 startthread 6 startthread 7 start thread 7 end thread 8 start thread 8 end thread 9 start thread 6 end thread 10 start thread 10 end thread 11 start thread 11 end thread 12 start thread 12 end thread 13 start thread 13 end thread 14 start thread 14 end thread 15 startthread 9 endthread 5 end thread 16 start thread 16 end thread 17 start thread 15 end thread 18 start thread 18 end thread 19 start thread 17 end thread 19 end * ** *** **** ***** ****** ******* ******** ********* ********** *********** ************ ************* ************** *************** **************** ***************** ****************** ******************* 主线程
(3)map 返回生成器
from concurrent.futures import ThreadPoolExecutor from threading import current_thread as ct def func(i): print("thread",i,ct().ident) print("thread %s end" % (i)) return i * "*" tp = ThreadPoolExecutor(5) res = tp.map(func,range(20)) tp.shutdown() for i in res: # 生成器 print(i)
执行结果:
thread 0 9336 thread 0 end thread 1 9336 thread 1 end thread 2 9336 thread 2 end thread 3 3348 thread 3 end thread 4 10116 thread 4 end thread 5 3348 thread 5 endthread thread thread7 8 9292 thread 8 end 6 thread 9 9336 thread 6 end thread9292 thread 9 end thread 11 10 9336 9292 threadthread 10 end thread 13 thread3348 thread 11 end thread 15 thread 7 end thread 16 12 9292 thread 15 end 14 3348 thread 16 end 10116 thread 14 endthread 17 3348 thread 17 end thread thread 19 3348 thread 19 end 10068933618 thread 13 end thread 12 end 9292 thread 18 end * ** *** **** ***** ****** ******* ******** ********* ********** *********** ************ ************* ************** *************** **************** ***************** ****************** *******************