ThreadPoolExecutor实现异步多线程
实现异步是三大步: #一,导入ThreadPoolExecutor
from concurrent.futures import ThreadPoolExecutor
#二,实例化executor对象(执行者) executor = ThreadPoolExecutor(max_workers=20)
#三,executor执行耗时函数 executor.submit("要执行的耗时函数",("耗时函数参数"))
举例:
import time from concurrent.futures import ThreadPoolExecutor executor = ThreadPoolExecutor(max_workers=20) list = [] # 子线程要执行的函数,一般这里的函数比较耗时,所以要用异步。列表要把线程完成的标志加入到全局列表中。 def a(c): time.sleep(c) print('我是一个线程') list.append('1') # 启动20个线程,注意这里,实现了异步,启动线程后,主线程继续往下运行 for x in range(20): # 这里,a()的参数传递方式如下 executor.submit(a,(5)) print('我是主线程') # 通过查看列表中元素个数来判定线程完成情况 while True: if len(list)== 20: break print(list)
判断全部线程是否结束,也可以用shutdown方法实现
import time from concurrent.futures import ThreadPoolExecutor executor = ThreadPoolExecutor(max_workers=20) list = [] # 子线程要执行的函数,一般这里的函数比较耗时,所以要用异步。列表要把线程完成的标志加入到全局列表中。 def a(c): time.sleep(c) print('我是一个线程') list.append('1') # 启动20个线程,注意这里,实现了异步,启动线程后,主线程继续往下运行 for x in range(20): # 这里,a()的参数传递方式如下 executor.submit(a,(5)) print('我是主线程') # shutdown方法等待全部线程结束 executor.shutdown(wait=True) print(list)
全世界的程序员们联合起来吧!