具有 numpy 函数的多处理池

时间:2021-02-10 23:41:28

标签: python arrays function numpy multiprocessing

我有一台带有 6 核的 i5-8600k,正在运行 Windows 10 计算机。我正在尝试使用 2 个 numpy 函数执行多处理。我事先提出了一个问题,但我没有成功运行该问题:issue,下面的代码来自该问题的答案。我试图同时运行 func1()func2(),但是,当我运行下面的代码时,它会一直运行下去。

import multiprocessing as mp
import numpy as np
num_cores = mp.cpu_count()

Numbers = np.array([1,2,3,4,5,6,7,8,9,10,11,12])
def func1():
     Solution_1 = Numbers + 10
     return Solution_1
def func2():
     Solution_2 = Numbers * 10
     return Solution_2

# Getting ready my cores, I left one aside
pool = mp.Pool(num_cores-1)
# This is to use all functions easily
functions = [func1, func2]
# This is to store the results
solutions = []
for function in functions:
    solutions.append(pool.apply(function, ()))

enter image description here

1 个答案:

答案 0 :(得分:1)

代码有几个问题。首先,如果你想在 Windows 中的 Jupyter Notebook 下运行它,那么你需要将你的工作函数 func1func2 放在一个外部模块中,例如,workers.py 并导入它们,然后意味着您现在需要将 Numbers 数组作为参数传递给工作人员,或者在初始化池时使用该数组初始化每个进程的静态存储。我们将使用名为 init_pool 的函数为您提供第二种方法,如果我们在 Notebook 下运行,也必须导入该函数:

workers.py

def func1():
     Solution_1 = Numbers + 10
     return Solution_1

def func2():
     Solution_2 = Numbers * 10
     return Solution_2

def init_pool(n_array):
    global Numbers
    Numbers = n_array

第二个问题是,在 Windows 下运行时,创建子进程或多处理池的代码必须位于受条件 if __name__ == '__main__': 控制的块内。第三,如果您只想运行两个并行的“作业”,那么创建大于 2 的池大小是很浪费的。第四,我认为最后,您使用了错误的池方法。 apply 将阻塞,直到提交的“作业”(即由 func1 处理的作业)完成,因此您根本无法实现任何程度的并行。您应该使用 apply_async

import multiprocessing as mp
import numpy as np
from workers import func1, func2, init_pool


if __name__ == '__main__':
    #num_cores = mp.cpu_count()
    Numbers = np.array([1,2,3,4,5,6,7,8,9,10,11,12])
    pool = mp.Pool(2, initializer=init_pool, initargs=(Numbers,)) # more than 2 is wasteful
    # This is to use all functions easily
    functions = [func1, func2]
    # This is to store the results
    solutions = []
    results = [pool.apply_async(function) for function in functions]
    for result in results:
        solutions.append(result.get()) # wait for completion and get the result
    print(solutions)

打印:

[array([11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]), array([ 10,  20,  30,  40,  50,  60,  70,  80,  90, 100, 110, 120])]

enter image description here

相关问题