线程/进程池的作用:
- 预先开启设定数量的线程,某个线程结束后可以让程序继续使用该线程;
- 配置多线程可以让程序并行处理,提高处理速度;
- 设置线程的最大数量,让系统不至于因为开启多个线程而出现内存/CPU溢出.。
线程/进程池
线程池的基类是 concurrent.futures 模块中的ThreadPoolExecutor 和 ProcessPoolExecutor两个子类,其中 ThreadPoolExecutor 用于创建线程池,而 ProcessPoolExecutor 用于创建进程池。
- Python的线程有GIL锁,是单核的;
- Python的进程都有独立的GIL锁,是多核的,但需要独立分配的内存空间,资源消耗大。
用法
使用线程池执行并发任务的步骤如下:
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()
注意:
- 线程无法保证函数执行顺序
- 可能会导致内存溢出