我希望主服务器将数据发送给工人以进行处理并从工人那里获得结果。但是,代码无法确定。我找不到原因,看来工人无法接收数据。代码如下。
from mpi4py import MPI
comm = MPI.COMM_WORLD
RANK = comm.Get_rank()
SIZE = comm.Get_size()
def task_master():
items = list(range(2000))
results = []
totalItem = len(items)
while len(items) > 0:
status = MPI.Status()
print('Master before recv %d'%RANK)
result = comm.recv(status=status)
print('Master after recv %d'%RANK)
if result:
results.append(result)
rnk = status.Get_source()
print('Master receive from %d'%rnk)
print('Master before send %d'%RANK)
comm.send([items.pop()], dest=rnk)
print('Master after send %d'%rnk)
print("Finish: {}/{} {}".format(len(results), totalItem, str(result)))
for i in range(SIZE):
comm.send(None, dest=i)
def task_worker():
while True:
print('Worker before send %d'%RANK)
comm.send(1, dest=0)
print('Worker before recv %d'%RANK)
data = comm.recv(source=0)
print("%d Received from 0"%RANK)
print("%d data:%s"%(RANK, str(data)))
if not data:
break
print("End of %d"%RANK)
if __name__ == '__main__':
init_logger(level = logging.INFO)
if RANK == 0:
task_master()
else:
task_worker()
我使用python 3.7。 open-mpi和mpi4py均为最新版本。只需运行mpiexec -n 10 python