Skip to main content
 首页 » 编程设计

Python:使用 mpi4py 通过 spawn 将数组广播到其他脚本

2025年05月04日9haluo1

我正在尝试编写两个脚本,一个是主脚本,一个是工作脚本,其中主脚本将生成多个工作进程,然后将一个 numpy 数组广播到生成的工作进程。从在线查看 mpi4py 的(模糊)教程的数量来看,我觉得我理解了这个概念,但是我编写的任何测试代码都不会成功地将数组发送给工作人员。我没有收到错误,但他们从未收到数组。

谁能给我一个清楚的例子,说明如何使用 mpi4py、spawn 和 bcast 将数组广播到多个 spawned worker 脚本?谢谢!

更新:示例:

主脚本:

#! /usr/bin/env python 
# master test 
 
import sys,time 
from mpi4py import MPI 
import numpy as np 
 
comm2    = MPI.COMM_WORLD 
rank     = comm2.Get_rank() 
mpisize  = comm2.Get_size() 
 
initcomm = MPI.COMM_SELF.Spawn(sys.executable, \ 
                           args=['test2.py'], \ 
                           maxprocs=5) 
 
# Initialise the programs 
test = np.array([1,2,3], 'i') 
print("About to broadcast {0} from rank {1}".format(test, rank)) 
initcomm.Bcast([test, MPI.INT], root=0) 
initcomm.Disconnect() 

工作脚本:

#! /usr/bin/env python 
# child test 
 
import sys,time 
from mpi4py import MPI 
import numpy as np 
 
comm2    = MPI.COMM_WORLD 
rank     = comm2.Get_rank() 
mpisize  = comm2.Get_size() 
 
initcomm = MPI.Comm.Get_parent() 
 
test = np.zeros(3, 'i') 
print("Bcast coming to rank {0}".format(rank)) 
initcomm.Bcast([test, MPI.INT], root=0) 
print("Received {0}".format(test)) 
initcomm.Disconnect() 

请您参考如下方法:

您需要将主脚本中的 Bcast 更改为:

initcomm.Bcast([test, MPI.INT], root=MPI.ROOT) 

如果设置为0,master会认为root在remote/worker组中排名0,程序会挂起。