/** * Modified the original code from * Open Systems Laboratory * http://www.lam-mpi.org/tutorials/ * Indiana University * * Compute 2^16 on a 4 processors ring * Each processor is allowed only one multiplication after receiving and before * sending * * Compile and link with: /opt/mpich_mx/bin/mpicc -static -o ring ring.c */ #include #include "mpi.h" # define two 2 int main(int argc, char *argv[]) { MPI_Status status; int num[2],val,rank,size,tag,next,from,i,result=1; /* Start up MPI */ MPI_Init(&argc, &argv); MPI_Comm_rank(...); MPI_Comm_size(...); if (size != 4) { printf("\nNot enough processors\n"); MPI_Finalize(); return 0; } /* Arbitrarily choose 201 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 = 201; next = (rank + 1) % size; from = (rank + size - 1) % size; /* If we are the "master" process, initialize val to 1, make the first multiplication and send it to the next process*/ if (rank == 0) { num[0]=...; num[1] = 1; num[1]*=...; printf("Process %d sending %d to %d\n", rank, num[1], next); ... } /* Pass the message around the ring. The exit mechanism works as follows: the message (2 positive integers) is passed around the ring. Each time it passes rank 0, num[0] is decremented. When each processes receives the message with num[0]=0, 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. */ do { ... printf("Process %d received %d\n", rank,num[1]); /* Do the multiplication */ ... /** If process is 0, decrement num[0] and print a message */ ... ... printf("Process %d sending %d to %d\n", rank, num[1], next); ... } while (num[0] > 0); printf("Process %d exiting\n", rank); /* The last message of process 3 need to be received by process 0 * before the program can exit */ if (rank == 0) { ... /* print the result */ for (i=0; i<16; i++) result*=two; printf("\n 2^16=%d\n", result); printf("\n computed 2^16=%d\n", num[1]); } /* Quit */ MPI_Finalize(); return 0; }