/* * Open Systems Laboratory * http://www.lam-mpi.org/tutorials/ * Indiana University * * MPI Tutorial * * Mail questions regarding tutorial material to lam at lam dash mpi dot org */ #include #include int main(int argc, char** argv) { int rank, size; int done; int left_dest, right_dest; const int tag = 4; double x, left_x, right_x; MPI_Request req[4]; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); if (rank == 0) { printf("Enter the number of iterations: "); scanf("%d", &done); } MPI_Bcast(&done, 1, MPI_INT, 0, MPI_COMM_WORLD); x = (rank == 0 || rank == size - 1) ? 1 : 2; left_x = (rank == 0) ? 1 : 2; right_x = (rank == size - 1) ? 1 : 2; left_dest = (rank == 0) ? MPI_PROC_NULL : rank - 1; right_dest = (rank == size - 1) ? MPI_PROC_NULL : rank + 1; while (--done > 0) { /* Post receives from neighbors */ MPI_Irecv(&left_x, 1, MPI_DOUBLE, left_dest, tag, MPI_COMM_WORLD, &req[0]); MPI_Irecv(&right_x, 1, MPI_DOUBLE, right_dest, tag, MPI_COMM_WORLD, &req[1]); /* Post sends to neighbors */ MPI_Isend(&x, 1, MPI_DOUBLE, left_dest, tag, MPI_COMM_WORLD, &req[2]); MPI_Isend(&x, 1, MPI_DOUBLE, right_dest, tag, MPI_COMM_WORLD, &req[3]); /* Do local computation. Unfortunately, there is none. But this is where you would do it. */ /* Wait for all requests to complete */ MPI_Waitall(4, req, MPI_STATUSES_IGNORE); /* Calculate the average (using left_x and right_x) */ x = (right_x + left_x) / 2.0; } if (rank == 0) printf("Final average is: %lf\n", x); MPI_Finalize(); return 0; }