/* problem 3.7.1 in PPMPI * * Send a message from all processes with rank != 0 to process 0. * Process 0 prints the messages received. * * Input: none. * Output: contents of messages received by process 0. * * See Chapter 3, pp. 41 & ff in PPMPI. * * by John Weatherwax * * Try: * 1) Run MPI_Send then MPI_Recv * -Random ordering of printing statements * 2) Run MPI_Recv the MPI_Send * -Every process hangs waiting on the message it is supposed to recieve * 3) Alternate which process even send then recieve * odd are recieving and then sending. * -Random ordering of print statements. * */ #include #include #include "mpi.h" main(int argc, char* argv[]) { int my_rank; /* rank of process */ int p; /* number of processes */ int dest; /* rank of destination */ int recv; /* rank of receiver */ int tag = 0; /* tag for messages */ char messageS[100]; /* storage for message sent */ char messageR[100]; /* storage for message recieved */ MPI_Status status; /* return status for */ /* receive */ /* Start up MPI */ MPI_Init(&argc, &argv); /* Find out process rank */ MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); /* Find out number of processes */ MPI_Comm_size(MPI_COMM_WORLD, &p); /* Calculate who to SEND a message to: */ dest = (my_rank+1) % p; /* Calculate who to RECIEVE a message from: */ recv = ( (my_rank==0) ? (p-1) : (my_rank-1) ); /* Create message */ sprintf(messageS, "Greetings from process %d!",my_rank); if( my_rank % 2 == 0 ){ /* Use strlen+1 so that '\0' gets transmitted */ printf("Process %d sending: %s\n", my_rank, messageS); MPI_Send(messageS, strlen(messageS)+1, MPI_CHAR, dest, tag, MPI_COMM_WORLD); MPI_Recv(messageR, 100, MPI_CHAR, recv, tag, MPI_COMM_WORLD, &status); printf("Process %d recieved: %s\n", my_rank, messageR); }else{ MPI_Recv(messageR, 100, MPI_CHAR, recv, tag, MPI_COMM_WORLD, &status); printf("Process %d recieved: %s\n", my_rank, messageR); /* Use strlen+1 so that '\0' gets transmitted */ printf("Process %d sending: %s\n", my_rank, messageS); MPI_Send(messageS, strlen(messageS)+1, MPI_CHAR, dest, tag, MPI_COMM_WORLD); } /* Shut down MPI */ MPI_Finalize(); } /* main */