C   133
global mpi operations
Guest on 14th March 2023 12:17:35 AM


  1. include <stdio.h>
  2. #include <stdlib.h>
  3. #include <mpi.h>
  4.  
  5. int main(int argc, char *argv[])
  6. {
  7.         int rank, size;
  8.         double message, local_result, total_result_1, total_result_2;
  9.  
  10.         MPI_Init(&argc, &argv);
  11.         MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  12.         MPI_Comm_size(MPI_COMM_WORLD, &size);
  13.  
  14.         /* Synchronization.
  15.          * All process must reach here before continuing. */
  16.         MPI_Barrier(MPI_COMM_WORLD);
  17.         printf("synchronized ( node %d )\n", rank);
  18.         /* Synchronize again to ensure the "synchronized" messages are contiguous. */
  19.         MPI_Barrier(MPI_COMM_WORLD);
  20.  
  21.         /* An arbitrary message */
  22.         message = 0;
  23.         if (rank == 0)
  24.                 message = 5.6789;
  25.  
  26.         /* Broadcast this message */
  27.         MPI_Bcast(&message, 1, MPI_DOUBLE, 0 /* root */ , MPI_COMM_WORLD);
  28.  
  29.         /* Check if message received */
  30.         printf("node %d -- message %f\n", rank, message);
  31.  
  32.         /* Process dependent result */
  33.         local_result = 2.0 * rank;
  34.  
  35.         /* Reduce operations */
  36.         MPI_Reduce(&local_result, &total_result_1, 1, MPI_DOUBLE,
  37.                    MPI_MAX, 0 /* target_process */ , MPI_COMM_WORLD);
  38.  
  39.         MPI_Reduce(&local_result, &total_result_2, 1, MPI_DOUBLE,
  40.                    MPI_SUM, 0 /* target_process */ , MPI_COMM_WORLD);
  41.  
  42.         /* Only target node 0 has the global results */
  43.         if (rank == 0)
  44.                 printf
  45.                     ("results of global operations: %f %f <-- node 0 has results\n",
  46.                      total_result_1, total_result_2);
  47.  
  48.         /* Reduce operation followed by bcast. */
  49.         MPI_Allreduce(&local_result, &total_result_1, 1, MPI_DOUBLE,
  50.                       MPI_MAX, MPI_COMM_WORLD);
  51.  
  52.         MPI_Allreduce(&local_result, &total_result_2, 1, MPI_DOUBLE,
  53.                       MPI_SUM, MPI_COMM_WORLD);
  54.  
  55.         /* All nodes have the results */
  56.         printf("results of ALLREDUCE operations ( node %d ): %f %f\n",
  57.                rank, total_result_1, total_result_2);
  58.  
  59.         /* Clean up and exit */
  60.         MPI_Finalize();
  61.         exit(1);
  62. }

Raw Paste

Login or Register to edit or fork this paste. It's free.