2015-07-02 32 views
4

我是使用Python的MPI中的新手,我在这里遇到一些问题。这是我的代码:来自mpi4py程序的意外输出

from mpi4py import MPI 

comm = MPI.COMM_WORLD 
rank = comm.Get_rank() 

if rank == 0: 
     a = 1 
     comm.bcast(a, root=0) 
     s = comm.reduce(a, op=MPI.SUM) 
     print 'From process 0, sum =', s 
elif rank == 1: 
     b = 2 
     comm.bcast(b, root=1) 
     x = comm.reduce(b, op=MPI.SUM) 
     print 'From process 1, sum =', x 

我想打印:From process PROCESS_NUMBER, sum = 3

进程0打印正确,但过程1打印无。

我不明白为什么。任何人都可以帮我吗?

回答

3
  1. 任何集体操作(BcastReduce)应该呼吁所有 过程,所以它是不正确的地方它里面if rank == N 声明。
  2. 在第二次减少时,您必须指定root=1
  3. 分配需要在广播a = comm.bcast(a, root=0)

更正代码:

From process 0, sum = 3 
From process 1, sum = 6 

from mpi4py import MPI 

comm = MPI.COMM_WORLD 
rank = comm.Get_rank() 

if rank == 0: 
     a = 1 
else: 
     a = None 
a = comm.bcast(a, root=0) 
s = comm.reduce(a, op=MPI.SUM) 
if rank == 0: 
     print 'From process 0, sum =', s 

if rank == 1: 
     b = 2 
else: 
     b = None 
b = comm.bcast(b, root=1) 
x = comm.reduce(b, op=MPI.SUM, root=1) 

if rank == 1: 
     print 'From process 1, sum =', x 

3个上运行的进程的结果

1

comm.reduce(a, op=MPI.SUM)对应于MPI_Reduce():总和只在根进程上可用。

如果您希望在传播者的每个过程中都可以使用总和,您可以使用comm.allreduce(a, op=MPI.SUM)。它对应于MPI_Allreduce()。请参阅this page以了解更多关于MPI_Reduce()MPI_Allreduce()之间的差异。