一.基础介绍
当我们需要执行的任务较多时,例如爬取多页数据,需要创建多个线程或者进程来提高效率,而一个一个创建线/进程就比较麻烦,这时我们就可以使用线程池/进程池。
线程池的作用就是开辟一些线程,我们直接给线程池提交任务,线程任务的调度交给线程池来完成。
线程池的基类是 concurrent.futures 模块中的 Executor,Executor 提供了两个子类,即 ThreadPoolExecutor 和 ProcessPoolExecutor,其中 ThreadPoolExecutor 用于创建线程池,而 ProcessPoolExecutor 用于创建进程池。
使用线程池来执行线程任务的步骤如下:
1. 调用 ThreadPoolExecutor 类的构造器创建一个线程池。
2. 定义一个普通函数作为线程任务。
3. 调用 ThreadPoolExecutor 对象的 submit() 方法来提交线程任务。
4. 当不想提交任何任务时,调用 ThreadPoolExecutor 对象的 shutdown() 方法来关闭线程池。
二.python实例学习
from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor
def