#include #include using namespace std; const int ROUNDS{10}; void TossTheBallRandom(int value, int rank, int size); void TossTheBall(int value, bool &finished, int rank, int size); void GetMessage(int & value, bool & finished, int rank, int size); // some custom tags const int BALL_PASS{1}; const int EXIT_PASS{2}; int main(int argc, char * argv[]) { MPI_Init(&argc, &argv); int value{0}; bool finished{false}; int rank, size; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); srand(time(nullptr) * (rank+1)); // rank 0 starts off by throwing the ball to everyone. if (rank == 0) { TossTheBallRandom(value, rank, size); } while (not finished) { GetMessage(value, finished, rank, size); TossTheBall(value, finished, rank, size); } if (rank == 0) { for(int i = 1; i < size; ++i) { cout << rank << " sending an exit to " << i << endl; MPI_Send(&value, 0, MPI_INT, i, EXIT_PASS, MPI_COMM_WORLD); } } MPI_Finalize(); return 0; } void GetMessage(int & value, bool & finished, int rank, int size){ MPI_Status status; int tmp; MPI_Probe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status); cout << endl; cout << "\t\tThe message came from " << status.MPI_SOURCE << endl; cout << "\t\tThe message had tag " << status.MPI_TAG << endl; int count; MPI_Get_count(&status, MPI_INT, &count); cout << "\t\tThe message had " << count << " integers " << endl; cout << endl; if (status.MPI_TAG == EXIT_PASS) { MPI_Recv(&tmp, 0, MPI_INT, MPI_ANY_SOURCE, EXIT_PASS, MPI_COMM_WORLD, &status); finished = true; cout << "\t" << rank << " got an exit " << endl; } else { MPI_Recv(&value, 1, MPI_INT, MPI_ANY_SOURCE, BALL_PASS, MPI_COMM_WORLD, &status); cout << "\t" << rank << " got " << value << " from " << status.MPI_SOURCE << endl; } } void TossTheBall(int value, bool &finished, int rank, int size) { if (value == ROUNDS) { if (rank != 0) { cout << rank << " Sending " << value << " back to 0" << endl; MPI_Send (&value, 1, MPI_INT, 0, BALL_PASS, MPI_COMM_WORLD); } else { finished = true; } } else { TossTheBallRandom(value, rank, size); } } void TossTheBallRandom(int value, int rank, int size){ int dest = rand() % size; while (dest == rank) { dest = rand() % size; } ++value; cout << rank << " sending a " << value << " to " << dest << endl; MPI_Send (&value, 1, MPI_INT, dest, BALL_PASS, MPI_COMM_WORLD); }