我是使用Python的MPI新手,我在这里遇到了一些问题。这是我的代码:
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打印无。
我无法理解为什么。有谁可以帮助我?
答案 0 :(得分:3)
Bcast
,Reduce
)
进程,因此将它放在if rank == N
内是不正确的
言。root=1
。a = comm.bcast(a, root=0)
更正后的代码:
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个进程上运行的结果:
From process 0, sum = 3
From process 1, sum = 6
答案 1 :(得分:1)
comm.reduce(a, op=MPI.SUM)
对应MPI_Reduce()
:总和仅适用于根进程。
如果您希望在通信器的每个进程中都可以使用该总和,则可以使用comm.allreduce(a, op=MPI.SUM)
。它对应MPI_Allreduce()
。请参阅this page,详细了解MPI_Reduce()
和MPI_Allreduce()
之间的区别。