#include #include #include int main(int argc, char** argv) { MPI_Init(&argc, &argv); int size = 0; MPI_Comm_size(MPI_COMM_WORLD, &size); // what is the rank of this process? int rank = 0; MPI_Comm_rank(MPI_COMM_WORLD, &rank); // should only run if there are exactly two processes if(size != 2) { if(!rank) std::cerr << "Run with two parallel processes only. Not with " << size << " processes.\n"; MPI_Finalize(); return EXIT_FAILURE; } int64_t limit = std::atoi(argv[1]); if(!rank) std::cout << "MPI ping-pong count up to " << limit << ".\n"; // initialize counter to 0 int64_t counter = 0; int64_t buffer = 0; while(counter < limit) { // increment counter and send from 0 to 1 if(rank == 0) MPI_Send(&(++counter), 1, MPI_INT64_T, 1, 1, MPI_COMM_WORLD); if(rank == 1) { MPI_Recv(&buffer, 1, MPI_INT64_T, 0, 1, MPI_COMM_WORLD, MPI_STATUS_IGNORE); counter = buffer; } if(counter == limit) break; // increment counter and send back from 1 to 0 if(rank == 1) MPI_Send(&(++counter), 1, MPI_INT64_T, 0, 2, MPI_COMM_WORLD); if(rank == 0) { MPI_Recv(&buffer, 1, MPI_INT64_T, 1, 2, MPI_COMM_WORLD, MPI_STATUS_IGNORE); counter = buffer; } if(!rank && (counter % (limit/10) == 0)) std::clog << "\n\tcounter = " << counter << "."; } if(!rank) std::cout << "\nDone: counter = " << counter << ".\n"; MPI_Finalize(); }