MPI_Bcast难度:如何确保"正确"的根播放

use*_*516 3 c c++ mpi

我对MPI(使用C)相对较新,并且在使用MPI_Bcast向所有进程发送int时遇到了一些麻烦.

在我的代码中,我决定哪个等级是for循环中的root,其中不同的进程负责循环的不同元素.然后,我希望Bcast从root到所有进程的结果,除了所有非root进程都不知道谁预期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
Run Code Online (Sandbox Code Playgroud)

当我执行此代码时,无论bcastroot默认值(所有非根进程的值)与root竞争,因此X未正确广播.我不知道X的值,也不能事先预测根,所以我不能提前定义它.

我尝试初始化bcastroot = -1,然后将其设置为rank,但这不起作用.有没有办法在不为所有进程设置root的情况下Bcast这个值?

谢谢,JonZor

Jer*_*ock 6

没有办法做MPI_Bcast接收器不知道根是什么的地方.如果你知道只有一个root,你可以先做一个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);
Run Code Online (Sandbox Code Playgroud)

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