/* $Id: ring.c 1084 2006-08-29 12:55:26Z olau $ */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mpi.h>
#include "../../globaldefs.h"

#define ROOT                (0)


int main(int argc, char *argv[])
{
  int myrank, size;
  int recv_buf, send_buf;
  int right, left;
  MPI_Status stat;
#ifndef DEADLOCK
  MPI_Request req;
#endif /* DEADLOCK */

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

  if (size < 2) {
    printf("Fehler: Ring muss mindestens zwei Knoten haben.\n");
    MPI_Finalize();
    return 1;
  }

  right = (myrank + 1) % size;
  left  = (myrank - 1 + size) % size;

  send_buf = myrank;

#ifdef DEADLOCK
  MPI_Ssend(&send_buf, 1, MPI_INTEGER, right, 31337, MPI_COMM_WORLD);
  MPI_Recv(&recv_buf, 1, MPI_INTEGER, left, 31337, MPI_COMM_WORLD, &stat);
#else
  MPI_Issend(&send_buf, 1, MPI_INTEGER, right, 31337, MPI_COMM_WORLD, &req);
  MPI_Recv(&recv_buf, 1, MPI_INTEGER, left, 31337, MPI_COMM_WORLD, &stat);
  MPI_Wait(&req, &stat);
#endif /* DEADLOCK */

  printf("#%02d empfängt Token %02d\n", myrank, recv_buf);

  // Aufräumen
  MPI_Finalize();

  return 0;
}
