python - Python 的 ThreadPoolExecutor 会终止空闲线程吗?
问题描述
当池没有被大量使用时,Python 的 ThreadPoolExecutor 会终止空闲线程以减少资源使用吗?
解决方案
不,但是如果已经有空闲线程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
推荐阅读
- ios - 可聚焦不适用于 tvOS 中 SwiftUI 中的文本字段
- javascript - 显示隐藏 HTML5 隐藏文本字段的错误
- javascript - 在 4.2 版以后的 nodejs 中执行字符串 MongoDb Query 的 db.eval() 的替代方法是什么?
- javascript - 如何让手机像在桌面上滚动一样?
- c - 如何从C中的十六进制中提取RGB?
- html - 两个相同的 html 表格显示不同
- azure - 如何将变量传递给 azure devops 管道中的 SqlAzureDacpacDeployment@1 任务
- android - TextInputLayout 的概述文本字段
- javascript - 更改子元素位于顶部的 css
- r - 如何修复阻止 plot_cells(cds) 运行的重复列名?