1
votes

I have declared int value in my main, and all of the processes has inicialized this value. All of them are storing value, which I want to write on the screen after computing is finished. Is Broadcast a solution? E.g. how to implement it?

int i;
int value;
  MPI_Status status;
  MPI_Init(&argc, &argv);
  MPI_Comm_size(MPI_COMM_WORLD,&numtasks);
  MPI_Comm_rank(MPI_COMM_WORLD;&myrank);

  left =  (myrank - 1); if (left < 0) left = numtasks-1;
  right = (myrank + 1); if (right >= numtasks) right = 0;

if(myrank==0){
     value=value+myrank;
      MPI_Send(value,MPI_INT,right,99,MPI_COMM_WORLD);
      MPI_Recv(value,MPI_INT,left,99,MPI_COMM_WORLD,&status);

  }
  else if(myrank==(numtasks-1)){

      MPI_Recv(value,MPI_INT,left,99,MPI_COMM_WORLD,&status);
      value=value+myrank;
      MPI_Send(value,MPI_INT,right,99,MPI_COMM_WORLD);


  }
  else{
      MPI_Recv(value,MPI_INT,left,99,MPI_COMM_WORLD,&status);
      value=value+myrank;
      MPI_Send(value,MPI_INT,right,99,MPI_COMM_WORLD);
  }

Theese should make logical circle. I do one computing (sum of all ranks), and in process 0 I get result. This result (for 4 processes it will be 6) I want to be printed by each of the processes after this computing. But I don't see how to use barrier exactly and where.

There is also one thing, after all N-1 sendings (where N is number of processes) I should have sum of all ranks in each of processes. In my code I get this sum only into process 0... It might be a bad approach :-(

1

1 Answers

0
votes

Some more detail about the structure of your code would help, but it sounds like you can just use MPI_Barrier. Your processes don't need to exchange any data, they just have to wait until everyone reached the point in your code where you want the printing to happen, which is exactly what Barrier does.


EDIT: In the code you posted, the Barrier would go at the very end (after the if statement), followed by printf(value).

However, your code will not compute the total sum of all ranks in all nodes, since process i only receives the summed ranks of the first i-1 processes. If you want each process to have the total sum at the end, then replacing Barrier with Broadcast is indeed the best option. (In fact, the entire if statement AND the Broadcast could be replaced by a single MPI_Reduce() call, but that wouldn't really help you learn MPI. :) )