/* // ====================== mpi_scatter_reduce01.c ====================== // // Master distributes (scatters) an array across proccesses. // Processes add their elements, then combine sum in master // through a reduction operation // ==================================================================== */ #include #include main( int argc, char** argv) { int MyPE, //My logical process number NumPE, //Number of processes i; //loop index variable float A[16], //Global array MyA[4], //My portion of A MySum, //My partial sum Sum; //Total sum MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &MyPE); MPI_Comm_size(MPI_COMM_WORLD, &NumPE); //Master fill array (analogous to a read operation) if (MyPE == 0) { for (i = 0; i < 16; i ++) { A[i] = i + 1; } } //Scatter array among all processes - each process gets //4 contiguous entries of A MPI_Scatter(A, 4, MPI_FLOAT, MyA, 4, MPI_FLOAT, 0, MPI_COMM_WORLD); printf("PE %d: MyA is - ", MyPE); for (i = 0; i < 4; i ++) { printf("%f ", MyA[i]); } printf("\n"); //Calculate sums, then reduce to master process MySum = 0; for (i = 0; i < 4; i ++) { MySum += MyA[i]; } MPI_Reduce(&MySum, &Sum, 1, MPI_FLOAT, MPI_SUM, 0, MPI_COMM_WORLD); if (MyPE == 0) { printf("Total Sum is: %f\n", Sum); } MPI_Finalize(); return 0; }