如果我想列出每个传播者的变量id,我怎么能这样做?以下是尝试证明这一想法:
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, dtest=comm.rank)
mpi_id_list = []
for i in range(comm.size):
mpi_id_list.append( comm.recv(source=i, tag=11))
print mpi_id_list
答案 0 :(得分:1)
在MPI中,每个comm.send(...,dest=x)
都应与等级comm.recv(...)
进程执行的x
匹配。所有消息都可以发送到等级0的进程,进程0必须接收所有这些消息。该操作是称为缩减的集体操作。
通过键入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示例,请参阅here。例如,您受到comm.allreduce()
操作的诱惑:
list=comm.allreduce([mpi_id])
print list