mpirun python串行并行混合?

时间:2016-05-20 18:23:52

标签: python mpi

我是mpi4py包的新手。我正在使用此命令运行我的代码。 mpirun -np 4 python test.py我的任务是根据程序中给定的顺序顺序打印“Hello World”4次,但“只执行一次”。我应该如何在我的代码中指定,以便下一个命令应该等待完成上一个命令。

Hello, World! I am process 2 of 4 on sas32.
do it only once 2
Hello, World! I am process 3 of 4 on sas32.
Hello, World! I am process 0 of 4 on sas32.
do it only once 1
Hello, World! I am process 1 of 4 on sas32.

我的回答是打印

  do it only once 1
  Hello, World! I am process 2 of 4 on sas32.
  Hello, World! I am process 3 of 4 on sas32.
  Hello, World! I am process 0 of 4 on sas32.
  Hello, World! I am process 1 of 4 on sas32.
  do it only once 2

但我希望我的回答

C20:G30

1 个答案:

答案 0 :(得分:0)

您需要使用MPI_Barrier来同步流程:

from mpi4py import MPI
import sys

size = MPI.COMM_WORLD.Get_size()
rank = MPI.COMM_WORLD.Get_rank()
name = MPI.Get_processor_name()

if rank==1:
   print('do it only once %d'%rank)

MPI.COMM_WORLD.Barrier()
print("Hello, World! I am process %d of %d on %s."% (rank, size, name))
MPI.COMM_WORLD.Barrier()

if rank==2:
    print('do it only once %d'%rank)    

输出:

$ mpiexec -n 5 python mpibarrier.py 
do it only once 1
Hello, World! I am process 0 of 5 on abc.
Hello, World! I am process 2 of 5 on abc.
Hello, World! I am process 3 of 5 on abc.
Hello, World! I am process 4 of 5 on abc.
Hello, World! I am process 1 of 5 on abc.
do it only once 2

MPI_finalize将终止你的mpi会话;最终确定后你不能再打电话了。