MPI Duck, Duck... Goose! Kays Solution

From Education

Jump to: navigation, search

Kay's Solution

WARNING: This has no usage statement. Gasp!

#include <stdio.h>
#include <mpi.h>
#define SERVER 0
#define TRUE 1
#define CLOCKWISE 42
#define WIDDER 43


int main(int argc, char **argv) {
  
 int rank, size, goose, dest, tag; 
 MPI_Status status;

 MPI_Init(&argc, &argv);
 MPI_Comm_rank(MPI_COMM_WORLD,&rank);
 MPI_Comm_size(MPI_COMM_WORLD,&size);

 // Seed the random number generator
 srand(time(NULL));

 // Start the ball rolling
 if (rank == SERVER) {
    goose = rand() % size;   
    // Send to the right
    printf("Process %d: I'm going to goose process %d...\n", rank, 
		goose);
    MPI_Send(&goose, 1, MPI_INT, (rank+1)%size, CLOCKWISE, MPI_COMM_WORLD);
 }
 
 while (TRUE) {
    MPI_Recv(&goose, 1, MPI_INT, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD,
		&status);

    if (goose == rank) {
       goose = rand() % size;
       printf("Process %d: I was goosed and now I'm going to get %d\n", 
 		rank, goose);
       if (status.MPI_TAG == CLOCKWISE) {
          tag = WIDDER;
          dest = rank-1;
 	  if (dest < 0) dest = size-1;
       } else {
          tag = CLOCKWISE;
          dest = (rank+1)%size;
       }
    } else {
      printf("Process %d: Passing along a message from %d...\n", rank,
 		status.MPI_SOURCE);
      tag = status.MPI_TAG;
      if (status.MPI_TAG == CLOCKWISE)	 dest = (rank+1)%size;
      else {
	dest = rank-1;
	if (dest < 0) dest = size-1;
      }

    }
    sleep(2);
    MPI_Send(&goose, 1, MPI_INT, dest, tag, MPI_COMM_WORLD);

 }

 MPI_Finalize();
}
Personal tools
SC Education sites