/* compile: /usr/local/mpich-1.2.0/bin/mpicc mess.passing.example.c run : nice /usr/local/mpich-1.2.0/bin/mpirun -np 5 a.out To understand the program, draw the processors and slowly draw each message. All statements after MPI_Init are executed by (-np) 5 processes, PIDs are 0..P-1. */ #include #include /* a variable needeed for call, result not used */ static MPI_Status tmpstat; /* logical directions */ #define Left (PID-1) #define Right (PID+1) #define Any MPI_ANY_SOURCE /* Send and Receive operations DEST & SOURCE can be Left/Right or a PID (int 0..P-1) SOURCE can be Any */ /* Send the value of an int _variable_ VAR to destination process DEST */ #define Send(DEST, VAR) MPI_Send(&VAR, 1, MPI_INT, DEST, 0, MPI_COMM_WORLD) /* Receive an integer to an int variable VAR from destination process SOURCE */ #define Receive(SOURCE, VAR) MPI_Recv(&VAR, 1, MPI_INT, SOURCE, 0, MPI_COMM_WORLD, &tmpstat) int main(int argc, char **argv) { int PID, /* process-ID */ P; /* number of processes */ /* place own variables here */ int num, mess; /* keep these 3 calls */ MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &PID); MPI_Comm_size(MPI_COMM_WORLD, &P); /* actual code starts here */ /* Send a number right, return back left */ if (PID == 0) { /* 0 |-> */ num = 42; } else { /* ->| */ Receive(Left, num); } if (PID != P-1) { /* |-> */ Send(Right, num); /* |<- */ Receive(Right, mess); } else { /* Rightmost one does not send further right */ /* just senpar the same back */ mess = num; } /* All print just for debugging */ printf("Pros: %d, num: %d mess: %d \n", PID, num, mess); if (PID != 0) { /* <-| */ Send(Left, mess); } /* keep this call */ MPI_Finalize(); exit(0); }