#include #include "mpi.h" int main(int argc, char *argv[]) { MPI_Status status; int num, rank, size, tag, next, from; // Start up MPI MPI_Init(&argc, &argv); // how many process do we have & which numer is mine? MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); // Arbitrarily choose 42 to be our tag. Calculate the rank of the // next process in the ring. Use the modulus operator so that the // last process "wraps around" to rank zero. tag = 42; next = ...; from = ...; // If we are the "console" process, get a integer from the user to // specify how many times we want to go around the ring if (rank == 0) { std::cout << "Enter the number of times around the ring: "; std::cin >> num; --num; std::cout << "Process " << rank << " sending " << num << " to " << next << std::endl; // Send integer 'num' to 'next' process ... } // Pass the message around the ring. The exit mechanism works as // follows: the message (a positive integer) is passed around the // ring. Each time is passes rank 0, it is decremented. When each // processes receives the 0 message, it passes it on to the next // process and then quits. By passing the 0 first, every process // gets the 0 message and can quit normally. while (1) { // get integer from 'from' process and store it to 'num' ... std::cout << "Process " << rank << " received " << num << std::endl; if (rank == 0) { num--; std::cout << "Process " << rank << " depremented num to " << num << std::endl; } std::cout << "Process " << rank << " sending " << num << " to " << next << std::endl; // Send integer 'num' to 'next' process ... if (num == 0) { std::cout << "Process " << rank << " exiting" << std::endl; break; } } // The last process does one extra send to process 0, which needs to // be received before the program can exit if (rank == 0) // get integer from 'from' process and store it to 'num' ... // cleanup MPI_Finalize(); return 0; }