Python 多线程 max_workers

Python multithreading max_workers

根据ThreadPoolExecutordocumentation

If max_workers is None or not given, it will default to the number of processors on the machine.

如果我不设置这样的值

ThreadPoolExecutor(max_workers=None)

如果我的值很低 (2) 会不会影响性能? python 是否已经为 None 值分配了所有 CPU 个进程 vs 仅为带有数字的值分配了 2 个进程?

首先,您似乎在 link 中引用了错误的文档部分,即针对进程而非线程的部分。 one for 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.


由于您使用的是线程而不是进程,因此假设您的应用程序是 IO 绑定的,而不是 CPU 绑定的,并且您将其用于 concurrency, not parallelism。您使用的线程越多,您获得的并发性就越高(在一定程度上),但您获得的 CPU 周期就越少(因为会有上下文切换)。您必须在典型的工作负载下测试您的应用程序,以了解最适合您的方法。对此没有普遍最优的解决方案。