Facebook
From Sweltering Gorilla, 6 Years ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 233
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <unistd.h>
  4. #include <mpi.h>
  5.  
  6. int main(int argc, char **argv)
  7. {
  8.         int myrank;
  9.         int comm_size;
  10.         int message;
  11.         int number;
  12.         MPI_Status status;
  13.         MPI_Init(&argc, &argv);
  14.         sleep(5);
  15.         MPI_Comm_rank(MPI_COMM_WORLD, &myrank);
  16.         MPI_Comm_size(MPI_COMM_WORLD, &comm_size);
  17.  
  18.         int cs = comm_size-1;
  19.  
  20.         if(myrank==0)
  21.         {
  22.                 number = 27;
  23.                 printf("Process %d: Sending number %d to process %d.\n", myrank, number, (myrank+1)%comm_size);
  24.                 MPI_Send(&number, 1, MPI_INT, (myrank+1)%comm_size, 0, MPI_COMM_WORLD);
  25.                 printf("Process %d: Number %d sent to process %d. Awaiting number from process %d.\n", myrank, number, (myrank+1)%comm_size, cs);
  26.                 MPI_Recv(&number, 1, MPI_INT, cs, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
  27.                 printf("Process %d: Number %d received from process %d. Finalizing...\n", myrank, number, cs);
  28.         }
  29.         else
  30.         {
  31.                 int next = (myrank+1)%comm_size;
  32.                 printf("Process %d: Awaiting a number from process %d.\n", myrank, myrank-1);
  33.                 MPI_Recv(&number, 1, MPI_INT, myrank-1, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
  34.  
  35.                 printf("Process %d: Number %d received from process %d. Adding %d to it...\n", myrank, number, myrank-1, 10-myrank);
  36.                 number = number + (10-myrank);
  37.  
  38.                 printf("Process %d: Resulting number: %d. Sending to process %d.\n", myrank, number, next);
  39.                 MPI_Send(&number, 1, MPI_INT, next, 0, MPI_COMM_WORLD);
  40.                 printf("Process %d: Number sent to process %d.\n", myrank, next);
  41.  
  42.         }
  43.         MPI_Finalize();
  44.         return 0;
  45. }
  46.