如果您不知道要发送多少条消息,那么您必须引入一条消息来标记消息结束。您可以通过使用特殊标签来通用地使用它。为了避免为终止消息提供不匹配的缓冲区,您可以使用probe
检查传入的消息类型
tag_data = 42
tag_end = 23
if rank == 0:
randNum = numpy.zeros(1)
print "Process before receiving random numbers"
else:
for i in range(0,np.random.randint(1,10),1):
randNum = numpy.zeros(1)
randNum = numpy.random.random_sample(1)
print "Process", rank, "iteration", i, "drew the number", randNum[0]
comm.Send(randNum, dest=0, tag=tag_data)
# send the termination message. Using the lower-case interface is simpler
comm.send(None, dest=0, tag=tag_end)
if rank == 0:
# For debugging it might be better to use a list of still active procsses
remaining = comm.Get_size() - 1
while remaining > 0:
s = MPI.Status()
comm.Probe(status=s)
# make sure we post the right kind of message
if s.tag == tag_data:
comm.Recv(randNum, s.source, tag=tag_data)
print "Process ", s.source, " received the number", randNum[0]
elif s.tag == tag_end:
# don't need the result here
print "Process ", rank, " is done"
comm.recv(source=s.source, tag=tag_end)
remaining -= 1
这有很多变体。例如,如果您知道某条消息是最后一条消息,则可以合并终止消息。