/* L-15 MCS 572 Mon 26 Sep 2016 : pipe_ring.c.
 * This program illustrates a manager/worker pipeline model
 * where the processors are aligned in a ring.
 * Compile this program as "mpicc -o pipe_ring pipe_ring.c",
 * and then run on p processors by "mpirun -np p pipe_ring". */

#include <stdio.h>
#include "mpi.h"

#define tag 100  /* tag for sending a number */

void manager ( int p );
/*
 * The manager prompts the user for a number
 * and passes this number to node 1 for doubling.
 * The manager receives from node p-1 the result. */

void worker ( int p, int i );
/*
 * Worker with identification label i of p 
 * receives a number,
 * doubles it and sends it to node i+1 mod p. */

int main ( int argc, char *argv[] )
{
   int i,p;
   MPI_Status status;

   MPI_Init(&argc,&argv);
   MPI_Comm_size(MPI_COMM_WORLD,&p);
   MPI_Comm_rank(MPI_COMM_WORLD,&i);

   if(i==0)
      manager(p);
   else
      worker(p,i);

   MPI_Finalize();
   return 0;
}

void manager ( int p )
{
   int n;
   MPI_Status status;

   printf("One pipeline cycle for repeated doubling.\n");
   printf("Reading a number...\n"); scanf("%d",&n);
   printf("Node 0 sends %d to the pipe...\n",n);
   fflush(stdout);
   MPI_Send(&n,1,MPI_INT,1,tag,MPI_COMM_WORLD);
   MPI_Recv(&n,1,MPI_INT,p-1,tag,MPI_COMM_WORLD,&status);
   printf("Node 0 received %d.\n",n);
}

void worker ( int p, int i )
{
   int n;
   MPI_Status status;

   MPI_Recv(&n,1,MPI_INT,i-1,tag,MPI_COMM_WORLD,&status);
   printf("Processor %d receives %d from node %d.\n",i,n,i-1);
   fflush(stdout);
   n *= 2;                      /* double the number */
   if(i < p-1)
      MPI_Send(&n,1,MPI_INT,i+1,tag,MPI_COMM_WORLD);
   else
      MPI_Send(&n,1,MPI_INT,0,tag,MPI_COMM_WORLD);
}
