线程池的基类是 concurrent.futures 模块中的ThreadPoolExecutor 和 ProcessPoolExecutor两个子类,其中 ThreadPoolExecutor 用于创建线程池,而 ProcessPoolExecutor 用于创建进程池。
使用线程池执行并发任务的步骤如下:
1,调用 ThreadPoolExecutor 类创建线程池;
2,定义一个函数作为线程任务;
3,调用 ThreadPoolExecutor 对象的 submit() 方法来提交线程任务;
4,调用 ThreadPoolExecutor 对象的 shutdown(wait = True) 方法来关闭线程池。
import time
from concurrent.futures import ThreadPoolExecutor
pool = ThreadPoolExecutor(20)
def func(i):
print(str(i).center(10, '-'))
time.sleep(2)
def run():
for i in range(100):
pool.submit(func, i)
pool.shutdown(wait=True)
if __name__ == '__main__':
run()