#include #include #include #define START 0 #define END 100 int main(int argc, char** argv) { int rank, size; /* initialize MPI */ MPI_Init(&argc, &argv); /* get the rank (process id) and size (number of processes) */ MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); /* calculate the start and end points by evenly dividing the range */ int start = ((END - START) / size) * rank; int end = start + ((END - START) / size) - 1; /* the last process needs to do all remaining ones */ if (rank == (size - 1)) { end = END; } /* do the calculation */ int sum = 0, i; for (i = start; i <= end; i++) { sum += i; } /* debugging output */ printf("Process %d: sum(%d, %d) = %d\n", rank, start, end, sum); /* MPI communication: process 0 receives everyone elses sum */ if (rank == 0) { /* parent process: receive each partial sum and add it to ours - * now we no longer care about the order we receive them in */ int partial, i; MPI_Status status; for (i = 1; i < size; i++) { MPI_Recv(&partial, 1, MPI_INT, MPI_ANY_SOURCE, 0, MPI_COMM_WORLD, &status); /* see which process we are reading from */ printf("Process 0 got data from process %d.\n", status.MPI_SOURCE); sum += partial; } } else { /* worker process: send sum to process 0 */ MPI_Send(&sum, 1, MPI_INT, 0, 0, MPI_COMM_WORLD); } /* now have process 0 display the results */ if (rank == 0) { printf("The final sum = %d.\n", sum); } /* quit MPI */ MPI_Finalize(); return 0; }