gpt4 book ai didi

python - 为什么 ThreadPoolExecutor 的默认 max_workers 是根据 CPU 数量决定的?

转载 作者:行者123 更新时间:2023-12-03 12:43:51 29 4
gpt4 key购买 nike

concurrent.futures.ThreadPoolExecutor 的文档说:

Changed in version 3.5: If max_workers is None or not given, it will default to the number of processors on the machine, multiplied by 5, assuming that ThreadPoolExecutor is often used to overlap I/O instead of CPU work and the number of workers should be higher than the number of workers for ProcessPoolExecutor.



我想了解为什么默认 max_workers值取决于 CPU 的数量。不管我有多少 CPU,在任何时间点都只能运行一个 Python 线程。

让我们假设每个线程都是 I/O 密集型的,它只有 10% 的时间在 CPU 上,90% 的时间在等待 I/O。然后让我们假设我们有 2 个 CPU。我们只能运行 10 个线程来使用 100% 的 CPU。我们不能再使用 CPU,因为在任何时间点都只有一个线程在运行。即使有 4 个 CPU,也是如此。

那么为什么是默认的 max_workers根据CPU数量决定?

最佳答案

检查处理器数量比检查程序的 I/O 限制要容易得多,尤其是在线程池启动时,当您的程序还没有真正开始工作时。没有什么比默认值更好的了。

此外,添加默认值是一个漂亮的 low-effort , low-discussion改变。 (以前,没有默认值。)尝试变得花哨会是更多的工作。

也就是说,变得更狂热可能会有所返回。也许是某种根据负载调整线程数的动态系统,因此您不必在信息最少的时候决定计数。不过,除非有人写,否则它不会发生。

关于python - 为什么 ThreadPoolExecutor 的默认 max_workers 是根据 CPU 数量决定的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56195679/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com