The Complexity With MPI_Bcast: How To Ensure The "Correct" Root Is Cast

I am relatively new to MPI (with C) and I have some problems using MPI_Bcast to send int to all processes.

In my code, I decide which rank is the root in the for loop, where different processes are responsible for a different element of the loop. Then I want Bcast to get the result from root to all processes, except that all non-root processes don't know who to expect bcast to, so don't get it.

The code block looks something like this:

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

      

When I execute this code, no matter which default bcastroot (the value for all non-root processes) is competing with the root, then X is not being passed correctly. I don't know the value of X and cannot predict the root in advance, so I cannot determine it in advance.

I tried initializing bcastroot = -1 and then setting it to rank, but that doesn't work. Is there a way that I can use this value without setting root for all processes?

Thanks, JonZor

+3


source to share


1 answer


There is no way to do MPI_Bcast

where the recipients don't know what the root is. If you know there will only be one root, you can do first MPI_Allreduce

to agree on this:

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);

      



then each rank will know the same root and you can make your broadcast.

+5


source







All Articles