MPI_Bcast inside If statement

I know this code is correct

#include <stdio.h>
#include "mpi.h"

int main(int argc, char * argv[]){
    int my_rank, p, n;

    MPI_Init(&argc, &argv);
    MPI_Comm_size(MPI_COMM_WORLD, &p);
    MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);

    if(my_rank == 0){
        scanf("%d", &n);
    }

    MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD);

    MPI_Finalize(); 
}

      

But what about this code. I asked someone and we got into the debate and he told me that this code is completely wrong.

#include <stdio.h>
#include "mpi.h"

int main(int argc, char * argv[]){
    int my_rank, p, n;

    MPI_Init(&argc, &argv);
    MPI_Comm_size(MPI_COMM_WORLD, &p);
    MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);

    if(my_rank == 0){
        scanf("%d", &n);
        MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD);
    }
    else {
        MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD);
    }

    MPI_Finalize(); 
}

      

I know this is not efficient, but I do not understand why it is wrong. I understand that each process will take a copy of the next program and work on it, so they will all use MPI_Bcast as if it were outside the if statement, so someone can explain to me what actually happens when I use MPI_Bcast inside if statements?

+3


source to share


1 answer


The first and second codes are semantically equivalent. Both are correct MPI programs. You can easily demonstrate that by compiling both with optimizations, the compiler generates the same assembly code.

$ mpicc -S first.c -O3
$ mpicc -S second.c -O3
$ diff first.s second.s
1c1
<   .file   "first.c"
---
>   .file   "second.c"

      



However, the first code is the best version. It has a simpler flow of control and is easier to show that it is correct in the sense that all ranks enter the barrier. This is important in order to ensure the MPI collective - all processes (in the communicator) must call them in the same order.

+3


source







All Articles