在 MPI 中,每个都comm.send(...,dest=x)
应该由comm.recv(...)
rank 进程执行的一个匹配x
。所有消息都可以发送到 rank 0 的进程,并且进程 0 必须接收所有这些消息。此操作是称为归约的集体操作。
通过键入以下代码可以在 4 个进程上执行mpirun -np 4 main.py
from mpi4py import MPI
comm = MPI.COMM_WORLD
obj = "I am an example. My ID is unique to each communicator."
mpi_id = 'rank %i has id %s'%(comm.rank, str(id(obj)))
comm.send(mpi_id, tag=11, dest=0)
mpi_id_list = []
if comm.rank==0:
mpi_id_list = []
for i in range(comm.size):
mpi_id_list.append( comm.recv(source=i, tag=11))
print mpi_id_list
#broadcasting the list
mpi_id_list = comm.bcast(mpi_id_list, root=0)
#now, the list is the same on all processes.
print "rank "+str(comm.rank)+" has list "+str(mpi_id_list)
请注意,此示例使用集体操作comm.bcast()
将结果列表广播到所有进程。有关不同集体操作的 mpi4py 示例,请参阅https://mpi4py.scipy.org/docs/usrman/tutorial.html。例如,您会被以下comm.allreduce()
操作所诱惑:
list=comm.allreduce([mpi_id])
print list