假设我想在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 ))
发生错误,似乎我未能将参数传递给函数,该怎么办?
<小时/>
编辑:
错误是:
---------------------------------------------------------------------------
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__
<小时/>
编辑2:
如果我无法在 python2.7
中执行此简单的并行操作,那么如何在 python3.5
中执行此操作?
Python 3.3 中添加了在上下文管理器中使用Pool
。由于您标记了 Python 2.7,因此无法使用 with
语法。
Documentation :
New in version 3.3: Pool objects now support the context management protocol – see Context Manager Types. __enter__()
returns the pool object, and __exit__()
calls 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()
我是一名优秀的程序员,十分优秀!