首页 > 解决方案 > 如何在多处理代码中重用池工作者?

问题描述

在下面的代码中,我收到有关“无法在模块main上获取属性 'f' ”的错误。我知道如何解决它:将池线和结果线都放在结果 2 的上方。

我的问题是为什么当前形式的代码不起作用。我正在处理更复杂的代码,我必须在两个不同的独立 for 循环中使用并行处理。现在,我在每个 for 循环的每次迭代中都有 pool=mp.Pool(3)。我在网上读到这很糟糕,因为在每次迭代中,我都会创建更多的池“工人”。如何将 pool = mp.Pool(3) 放在迭代之外,然后在我需要的代码的所有不同区域中使用相同的 Pool 工作程序?

作为记录,我正在使用 mac 来运行我的代码。

import numpy as np
import multiprocessing as mp

x = np.array([1,2,3,4,5,6])

pool = mp.Pool(3)

def f(x):
    return x**2

result = pool.map(f,x)

def g(x):
    return x + 1

result2 = pool.map(g,x)
print('result=',result,'and result2=',result2)

标签: pythonpython-3.xmultiprocessing

解决方案


当使用“fork”方法创建子进程(Mac OS 的默认值)时,进程在Pool创建时被分叉(基本上是复制)。这意味着在您的代码中,分叉的孩子尚未执行创建,f而是等待来自主进程的任务。

首先,您不应该直接在脚本中执行“活动”代码(除了定义函数、类、常量),而是将其移动到函数中。您的代码可能如下所示:

import numpy as np
import multiprocessing as mp


def f(x):
    return x**2

def g(x):
    return x + 1

def main():
    x = np.array([1,2,3,4,5,6])

    pool = mp.Pool(3)

    result = pool.map(f,x)
    result2 = pool.map(g,x)
    print('result=',result,'and result2=',result2)

# Should be nearly the only "active" statement
main()

或者在你的情况下可能更好,我猜:

import numpy as np
import multiprocessing as mp


def f(x):
    return x**2

def g(x):
    return x + 1

def proc_f():
    global x, pool
    return pool.map(f,x)

def proc_g():
    global x, pool
    return pool.map(g,x)

def main():
    global x, pool
    x = np.array([1,2,3,4,5,6])

    pool = mp.Pool(3)

    result = proc_f()
    result2 = proc_g()
    print('result=',result,'and result2=',result2)

# Should be nearly the only "active" statement
main()

推荐阅读