2015-07-02 55 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()之間的差異。