首页 > 解决方案 > Python 的 ThreadPoolExecutor 会终止空闲线程吗?

问题描述

当池没有被大量使用时,Python 的 ThreadPoolExecutor 会终止空闲线程以减少资源使用吗?

标签: pythonmultithreading

解决方案


不,但是如果已经有空闲线程Python 3.8+,它将避免创建新线程。

在下面的示例中,我将max_workers参数设置为 50,但只创建了 2 个线程(运行 5 个任务)并且线程数保持不变:

>>> from concurrent.futures import ThreadPoolExecutor
>>> def test(n):
...     return n * n
... 
>>> executor = ThreadPoolExecutor(max_workers=50)
>>> len(executor._threads)
0
>>> features = [executor.submit(test, i) for i in range(5)]
>>> len(executor._threads)
2
>>> [f.result() for f in features]
[0, 1, 4, 9, 16]
>>> len(executor._threads)
2
>>> features = [executor.submit(test, i) for i in range(10000)]
>>> len(executor._threads)
50

推荐阅读