MPI_Bcast的困难:如何确保"correct"根正在广播

Difficulty with MPI_Bcast: how to ensure that "correct" root is broadcasting

本文关键字:确保 correct 广播 Bcast 何确保 MPI      更新时间:2023-10-16

我对MPI(使用C)相对较新,在使用MPI_Bast向所有进程发送int时遇到了一些问题。

在我的代码中,我决定哪个秩是for循环中的根,其中不同的进程负责循环的不同元素。然后,我想从根向所有进程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

当我执行这段代码时,无论bcastrot默认值(所有非根进程的值)是什么,都会与root竞争,所以X没有正确广播。我不知道X的值,也不能预先预测根,所以我不能预先定义它。

我尝试过初始化bcastrot=-1,然后将其设置为rank,但这不起作用。有没有一种方法可以在不为所有进程设置根目录的情况下Bcast此值?

谢谢,JonZor

如果接收者不知道根是什么,就没有办法进行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);

然后每个等级都知道相同的根,你就可以进行广播了。