#include #include const int MAXITEMS = 10; int main(int argc, char **argv) { int size; int rank; int value; int root=0; int array[MAXITEMS]; int i; int anytag =0; double totalsum=0.0; double reciprocal; MPI_Status status; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &size); MPI_Comm_rank(MPI_COMM_WORLD, &rank); if (rank == 0) { srand(time(0)); for (i = 1; i < size; i++) { value = rand() % 10; printf("Root process 0 sending %d to process %d\n", value, i); MPI_Send(&value, 1, MPI_INT, i, anytag, MPI_COMM_WORLD); } value = rand() % 10; if (value == 0) reciprocal = 0; else reciprocal = 1.0/value; printf("Root process 0, value = %d, reciprocal = %lf\n", value, reciprocal); } else { MPI_Recv(&value, 1, MPI_INT, 0, anytag, MPI_COMM_WORLD, &status); printf("Hello from process %d out of %d Received: %d\n", rank, size, value); if (value == 0) reciprocal = 0.0; else reciprocal = 1.0/ value; printf("Process %d sending reciprocal (of %d) %lf to root 0", rank, value, reciprocal); MPI_Send(&reciprocal, 1, MPI_DOUBLE, 0, anytag, MPI_COMM_WORLD); printf("\n"); } MPI_Reduce(&reciprocal, &totalsum, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD); if (rank == 0) printf("*** Reporting from ROOT: Totalsum of reciprocals = %lf ***\n", totalsum); MPI_Finalize(); return 0; } /* mpicc -o reduceMPI reduceMPI.c mpirun N reduceMPI Root process 0 sending 5 to process 1 Root process 0 sending 2 to process 2 Root process 0 sending 9 to process 3 Root process 0 sending 4 to process 4 Root process 0 sending 4 to process 5 Root process 0, value = 4, reciprocal = 0.250000 Hello from process 2 out of 6 Received: 2 Process 2 sending reciprocal (of 2) 0.500000 to root 0 Hello from process 3 out of 6 Received: 9 Process 3 sending reciprocal (of 9) 0.111111 to root 0 Hello from process 5 out of 6 Received: 4 Process 5 sending reciprocal (of 4) 0.250000 to root 0 Hello from process 1 out of 6 Received: 5 *** Reporting from ROOT: Totalsum of reciprocals = 1.561111 *** Hello from process 4 out of 6 Received: 4 Process 4 sending reciprocal (of 4) 0.250000 to root 0 Process 1 sending reciprocal (of 5) 0.200000 to root 0 */