code noob
code noob

Reputation: 19

MPI - Trying print broadcast variable after the barrier, showing some other variable

I started with MPI learning. I have used a MPI_Barrier after MPI_Broadcast, in which i am broadcasting a variable to all the processes. But when I print the broad casted variable it is some value coming from memory but not from the broadcast. Not sure where I am doing wrong. Any suggestions please.

void main(int argc, char *argv[]){
  int x, comm_sz, my_rank;

  MPI_Init(NULL,NULL);
  MPI_Comm_size(MPI_COMM_WORLD, &comm_sz);
  MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);

  if(my_rank == 0){     
    x = strtol(argv[1], NULL, 10);
    MPI_Bcast(&x, 1, MPI_INT, 0, MPI_COMM_WORLD);
}

MPI_Barrier(MPI_COMM_WORLD);

if(my_rank != 0){
    printf("x is %d\n", x);
}

  MPI_Finalize();   
}

I just want to do some operations after the value is broad casted to all the processes.

Upvotes: 0

Views: 369

Answers (1)

Kris Lange
Kris Lange

Reputation: 146

The error lies in this area.

if(myRank == 0){      
    x = strtol(argv[1], NULL, 10);
    MPI_Bcast(&x, 1, MPI_INT, 0, MPI_COMM_WORLD);
}

MPI_Barrier(MPI_COMM_WORLD);

if(my_rank != 0){
    printf("x is %d\n", x);
}

MPI_Bcast should be run by all processes like so because otherwise the values of x will never be populated on the non-root (rank == 0) processes.

if(myRank == 0){      
    x = strtol(argv[1], NULL, 10);
}

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

if(my_rank != 0){
    printf("x is %d\n", x);
}

Since MPI_Bcast is blocking, the call to MPI_Barrier becomes unnecessary because a given process will not proceed until said process has received the broadcasted value of x.

See for more details

Upvotes: 2

Related Questions