// reduce.c // This program uses MPI_Reduce to collect data from all the processors - // including the root process - and apply some operation on all of this data. // In this program the operation is to sum all of the data collected from all // processes. The first parameter in MPI_Reduce is the value being sent from // each process. The second parameter is the variable storing the sum of // the data collected from all processes (in this case, the sum of all the // PIs). The fifth parameter, MPI_SUM, is the operation to be done on all // of the data collected from all processors. // The total sum, piSum, has a valid value only in the root process. // The root process is defined in the sixth parameter of MPI_Reduce ('source'). #include #include #include "mpi.h" int main(int argc, char **argv) { int rank, size; MPI_Status status; double pi, piSum; int i, count, source; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); count = 1; source = 0; if (rank == source) { pi = M_PI; printf("Rank %d is broadcasting %.10f\n", rank, pi); } MPI_Bcast(&pi, 1, MPI_DOUBLE, source, MPI_COMM_WORLD); if (rank != source) { printf("Rank %d receives %.10f from process %d\n", rank, pi, source); } MPI_Reduce(&pi, &piSum, 1, MPI_DOUBLE, MPI_SUM, source, MPI_COMM_WORLD); if (rank == source) { printf("Inside process %d, sum of pi's = %.10f\n", source, piSum); } MPI_Finalize(); return 0; } /* CRAY SV1: cc reduce.c mpirun -np 8 a.out Rank 0 is broadcasting 3.1415926536 Rank 2 receives 3.1415926536 from process 0 Rank 1 receives 3.1415926536 from process 0 Rank 3 receives 3.1415926536 from process 0 Rank 4 receives 3.1415926536 from process 0 Rank 5 receives 3.1415926536 from process 0 Rank 6 receives 3.1415926536 from process 0 Rank 7 receives 3.1415926536 from process 0 Inside process 0, sum of pi's = 25.1327412287 mpirun -np 4 a.out Rank 0 is broadcasting 3.1415926536 Rank 2 receives 3.1415926536 from process 0 Rank 3 receives 3.1415926536 from process 0 Rank 1 receives 3.1415926536 from process 0 Inside process 0, sum of pi's = 12.5663706144 */