我正在编写一组map(),reduce()和其他一些方便操作的并行版本。下面的代码返回一次正确的值,然后返回其余进程的None。我在这做错了什么?有没有办法让方法只返回一次?
我希望这样做能够在python的map()工作的任何实例中实现我的pmap()方法。
from mpi4py import MPI
import numpy as np
def _chunk(sizew, data):
size = int(np.floor(float(len(data))/float(sizew)))
ret = [None] * sizew
lower = lambda x: x*size
upper = lambda x: size+x*size if size+x*size<len(data)-1 else None
for i in range(0, sizew):
ret[i] = data[int(lower(i)):upper(i)]
return ret
def pmap(func, data):
w = MPI.COMM_WORLD
r = w.Get_rank()
s = w.Get_size()
data = _chunk(s, data)
d = w.scatter(data, root = 0)
f = w.bcast(func, root = 0)
m = map(eval(f), d)
m = w.gather(m, root = 0)
if m != None: return reduce(lambda x,y:x+y, m)
def hello():
w = MPI.COMM_WORLD
r = w.Get_rank()
s = w.Get_size()
print("Hello from " + str(r) + " of " + str(s) + " w = " + str(w))
def __main__():
#hello()
f = "lambda x: x**2"
a = pmap(f, [2,3,4,5])
print a
__main__()
我跑步:
mpiexec -n 3 python parallelpy.py
输出结果为:
None
None
[4, 9, 16, 25]