// // 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 using namespace std; 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); rank = MPI::COMM_WORLD.Get_rank(); size = MPI::COMM_WORLD.Get_size(); if (rank == 0) { cout << "Enter the number of iterations: "; cin >> done; } MPI::COMM_WORLD.Bcast(&done, 1, MPI::INT, 0); 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 req[0] = MPI::COMM_WORLD.Irecv(&left_x, 1, MPI::DOUBLE, left_dest, tag); req[1] = MPI::COMM_WORLD.Irecv(&right_x, 1, MPI::DOUBLE, right_dest, tag); // Post sends to neighbors req[2] = MPI::COMM_WORLD.Isend(&x, 1, MPI::DOUBLE, left_dest, tag); req[3] = MPI::COMM_WORLD.Isend(&x, 1, MPI::DOUBLE, right_dest, tag); // Do local computation. Unfortunately, there is none. But this // is where you would do it. // Wait for the receives to complete MPI::Request::Waitall(4, req); // Calculate the average (using left_x and right_x) x = (right_x + left_x) / 2.0; } if (rank == 0) cout << "Final average is: " << x << endl; MPI::Finalize(); return 0; }