我对MPI(使用C)相对较新,并且在使用MPI_Bcast向所有进程发送int时遇到了一些麻烦。
在我的代码中,我决定哪个等级是for循环中的root,其中不同的进程负责循环的不同元素。然后,我希望Bcast从根到所有进程的结果,除了所有非根进程都不知道谁预期bcast,所以不要接收它。
代码块看起来像这样:
for (iX=start; iX<end; iX++)
//start and end are the starting row and ending row for each processes, defined earlier
for (int iY=1; iY<nn; iY++)
// do some calculations
if (some condition)
int bcastroot = rank; // initialized above
int X = 111; // initialized above
else
//do other calculations
end
end
MPI_Bcast(&X, 1, MPI_INT, bcastroot, comm);
// remainder of code and MPI_FINALIZE
当我执行此代码时,无论bcastroot默认值(所有非根进程的值)与root竞争,因此X未正确广播。我不知道X的值,也不能事先预测根,所以我不能提前定义。
我尝试初始化bcastroot = -1,然后将其设置为排名,但这不起作用。有没有办法在没有为所有进程设置root的情况下Bcast这个值?
谢谢, JonZor
答案 0 :(得分:6)
没有办法做MPI_Bcast
,接收者不知道根是什么。如果您知道只有一个根,您可以先MPI_Allreduce
同意它:
int root, maybe_root;
int i_am_root = ...;
maybe_root = (i_am_root ? rank : 0);
MPI_Allreduce(&maybe_root, &root, 1, MPI_INT, MPI_MAX, MPI_COMM_WORLD);
然后每个等级都知道相同的根,你可以进行广播。