如何告诉 Pool 每个进程使用一定数量的内核?

How to tell Pool to use a certain number of cores per process?

我正在使用 multiprocessing.Pool 并行化项目中的一些计算。我如何告诉 Pool 在每个并行进程中使用 n 个(例如 4 个)内核?

假设我有 8 个内核。此代码是否会确保每个并行进程在 4 个内核上 运行?

from multiprocessing import Pool

def fun(in):
    print(in)

pool = Pool(2)
pool.map(fun, [1, 2, 3, 4, 5, 6])

不,您的代码将允许 Pool 创建两个进程(它们各自使用一个核心)并且 map() 将通过两个流中的指定函数处理您的项目集合。

我想你的意思可能是:

pool = Pool(4)

这意味着您的 fun 将同时在 4 个核心上 运行。

multiprocessing.Pool不会为每个进程创建多个线程,而是多个single-threaded进程。 "Parallel processes" 表示 运行 并行的多个进程,而不是某种内部并行的单个进程。

multiprocessing.Pool 中的每个进程将 运行 一次仅在一个核心上,因此您应该创建尽可能多的进程来使用核心 - 在这种情况下,如果您想要可能利用所有八个内核,您需要池中的八个进程:

pool = Pool(8)

您也可以完全不传递参数,并且 Pool 将自动分配与您拥有的 CPU 个内核一样多的进程。

Documentation for multiprocessing.Pool:

processes is the number of worker processes to use. If processes is None then the number returned by os.cpu_count() is used.

但是请注意,您实际上无法告诉 Pool 使用特定内核或特定数量的内核 - 该决定是由您的操作系统做出的,它通常会尝试在内核之间平均分配工作负载。