root/examples/Ring.java

/* [<][>][^][v][top][bottom][index][help] */

DEFINITIONS

This source file includes following definitions.
  1. main

   1 /*
   2  * Copyright (c) 2011      Cisco Systems, Inc.  All rights reserved.
   3  *
   4  * Simple ring test program
   5  */
   6 
   7 import mpi.* ;
   8 
   9 class Ring {
  10     static public void main(String[] args) throws MPIException {
  11 
  12 
  13         MPI.Init(args) ;
  14 
  15         int source;  // Rank of sender
  16         int dest;    // Rank of receiver
  17         int tag=50;  // Tag for messages
  18         int next;
  19         int prev;
  20         int message[] = new int [1];
  21 
  22         int myrank = MPI.COMM_WORLD.getRank() ;
  23         int size = MPI.COMM_WORLD.getSize() ;
  24 
  25         /* Calculate the rank of the next process in the ring.  Use the
  26            modulus operator so that the last process "wraps around" to
  27            rank zero. */
  28 
  29         next = (myrank + 1) % size;
  30         prev = (myrank + size - 1) % size;
  31 
  32         /* If we are the "master" process (i.e., MPI_COMM_WORLD rank 0),
  33            put the number of times to go around the ring in the
  34            message. */
  35 
  36         if (0 == myrank) {
  37             message[0] = 10;
  38 
  39             System.out.println("Process 0 sending " + message[0] + " to rank " + next + " (" + size + " processes in ring)");
  40             MPI.COMM_WORLD.send(message, 1, MPI.INT, next, tag);
  41         }
  42 
  43         /* Pass the message around the ring.  The exit mechanism works as
  44            follows: the message (a positive integer) is passed around the
  45            ring.  Each time it passes rank 0, it is decremented.  When
  46            each processes receives a message containing a 0 value, it
  47            passes the message on to the next process and then quits.  By
  48            passing the 0 message first, every process gets the 0 message
  49            and can quit normally. */
  50 
  51         while (true) {
  52             MPI.COMM_WORLD.recv(message, 1, MPI.INT, prev, tag);
  53 
  54             if (0 == myrank) {
  55                 --message[0];
  56                 System.out.println("Process 0 decremented value: " + message[0]);
  57             }
  58 
  59             MPI.COMM_WORLD.send(message, 1, MPI.INT, next, tag);
  60             if (0 == message[0]) {
  61                 System.out.println("Process " + myrank + " exiting");
  62                 break;
  63             }
  64         }
  65 
  66         /* The last process does one extra send to process 0, which needs
  67            to be received before the program can exit */
  68 
  69         if (0 == myrank) {
  70             MPI.COMM_WORLD.recv(message, 1, MPI.INT, prev, tag);
  71         }
  72 
  73         MPI.Finalize();
  74     }
  75 }

/* [<][>][^][v][top][bottom][index][help] */