--sas

mar4-msg-sum.c

Mar 10th, 2022
914
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.30 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <mpi.h>
  3. #include "l17.h"
  4.  
  5. int main(int argc, char** argv) {
  6.     int rc;
  7.     rc = MPI_Init(&argc, &argv);
  8.     L17_CHECK_ERROR(MPI_Init, rc);
  9.  
  10.     int size;
  11.     rc = MPI_Comm_size(MPI_COMM_WORLD, &size);
  12.     L17_CHECK_ERROR(MPI_Comm_size, rc);
  13.  
  14.     int rank;
  15.     rc = MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  16.     L17_CHECK_ERROR(MPI_Comm_rank, rc);
  17.  
  18.     if (size == 1) {
  19.         printf("No messages if there's only one process\n");
  20.         exit(1);
  21.     }
  22.  
  23.     if (rank == 0) {
  24.         int i = 0;
  25.         printf("Process %d: the number is %d\n", rank, i);
  26.  
  27.         rc = MPI_Send(&i, 1, MPI_INT, 1, 1, MPI_COMM_WORLD);
  28.         L17_CHECK_ERROR(MPI_Send, rc);
  29.  
  30.         rc = MPI_Recv(&i, 1, MPI_INT, size - 1, 1, MPI_COMM_WORLD, NULL);
  31.         L17_CHECK_ERROR(MPI_Recv, rc);
  32.         printf("Process %d: the number is %d\n", rank, i);
  33.     }
  34.     else {
  35.         int i;
  36.         rc = MPI_Recv(&i, 1, MPI_INT, rank - 1, 1, MPI_COMM_WORLD, NULL);
  37.         L17_CHECK_ERROR(MPI_Recv, rc);
  38.  
  39.         i += rank;
  40.         printf("Process %d: the number is %d\n", rank, i);
  41.  
  42.         int torank = (rank == size - 1) ? 0 : rank + 1;
  43.         rc = MPI_Send(&i, 1, MPI_INT, torank, 1, MPI_COMM_WORLD);
  44.         L17_CHECK_ERROR(MPI_Send, rc);
  45.     }
  46.  
  47.     MPI_Finalize();
  48.  
  49.     return 0;
  50. }
Advertisement
Add Comment
Please, Sign In to add comment