如何将(x,y)对列表映射到Pool.map中的函数f(x,y)?

时间:2017-05-25 02:45:52

标签: python python-2.7 python-3.x parallel-processing arguments

假设我想要在x-y平面上绘制密度,密度定义为:

def density(x,y):
    return x**2 +y**2

如果我要计算多个点(x1,y1), (x2,y2)...,那么我想要并行执行。我找到了文档multiprocessing并尝试执行以下操作:

pointsList = [(1,1), (2,2), (3,3)]
from multiprocessing import Pool
if __name__ == '__main__':
    with Pool() as p:
        print(p.map(density,pointsList ))

发生错误,似乎我没能将args传递给函数,怎么做?

编辑:

错误是:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-647-1e2a1f0007fb> in <module>()
      5 from multiprocessing import Pool
      6 if __name__ == '__main__':
----> 7     with Pool() as p:
      8         print(p.map(density,pointsList ))

AttributeError: __exit__

EDIT2:

如果我无法在python2.7中执行此简单并行操作,请问如何在python3.5中执行此操作?

2 个答案:

答案 0 :(得分:1)

在Python 3.3中添加了Pool在上下文管理器中的使用。由于您标记了Python 2.7,因此无法使用with语法。

Documentation

  

3.3版中的新功能:池对象现在支持上下文管理   protocol - 请参阅上下文管理器类型。 __enter__()返回池   对象和__exit__()来电terminate()

这里是你想要的工作示例,对于python 3.3+:

def density(args):
    x, y = args
    return x**2 +y**2

pointsList = [(1,1), (2,2), (3,3)]
from multiprocessing import Pool
if __name__ == '__main__':
    with Pool() as p:
        print(p.map(density,pointsList ))

由于你也使用Python 2.7,你只需要不使用上下文管理器并调用p.terminate()代替:

def density(args):
    x, y = args
    return x**2 +y**2

pointsList = [(1,1), (2,2), (3,3)]
from multiprocessing import Pool
if __name__ == '__main__':
    p = Pool()
    print(p.map(density,pointsList ))
    p.terminate()

答案 1 :(得分:0)

需要更改密度函数以解包元组参数

def density(z):
    (x,y) = z
    return x**2 +y**2

尝试不使用with并在完成后自行关闭池。 这种方式应兼容python 2和3

from multiprocessing import Pool  
pointsList = [(1,1), (2,2), (3,3)]
p = Pool()
print(p.map( density,pointsList ))
p.close()

或使用contextlib模块

from multiprocessing import Pool 
import contextlib
pointsList = [(1,1), (2,2), (3,3)]
with contextlib.closing(Pool()) as p:
    print(p.map( density,pointsList ))