mpi_ring.cpp
Go to the documentation of this file.
00001 #include "ros/ros.h"
00002 #include "mpi.h"
00003 #include <iostream>
00004 
00005 int main(int argc, char *argv[])
00006 {
00007     int next_rank;
00008     int prev_rank;
00009     double message;
00010     int message_tag = 201;
00011 
00012     // Start up MPI
00013 
00014     MPI::Init();
00015     int rank = MPI::COMM_WORLD.Get_rank();
00016     int nprocs = MPI::COMM_WORLD.Get_size();
00017  
00018     // Calculate the rank of the next process in the ring.  Use the
00019     // modulus operator so that the last process "wraps around" to
00020     // rank zero.
00021 
00022     next_rank = (rank + 1) % nprocs;
00023     prev_rank = (rank + nprocs - 1) % nprocs;
00024 
00025     // If we are the "master" process (i.e., MPI_COMM_WORLD rank 0),
00026     // put the number of times to go around the ring in the message.
00027 
00028     if (0 == rank) {
00029         ros::init(argc,argv,"mpi_node",ros::init_options::NoSigintHandler);
00030 
00031         message = 1000;
00032 
00033         ROS_INFO("Process 0 sending %f to %d/(%d processes in ring), with tag=%d",message,rank,next_rank,nprocs,message_tag);
00034         MPI::COMM_WORLD.Send(&message, 1, MPI::DOUBLE, next_rank, message_tag);
00035         ROS_INFO("Process 0 sent message(%f) to %d",message,next_rank);
00036     }
00037 
00038     // Pass the message around the ring.  The exit mechanism works as
00039     // follows: the message (a positive integer) is passed around the
00040     // ring.  Each time it passes rank 0, it is decremented.  When
00041     // each processes receives a message containing a 0 value, it
00042     // passes the message on to the next process and then quits.  By
00043     // passing the 0 message first, every process gets the 0 message
00044     // and can quit normally.
00045 
00046     while (1) {
00047         MPI::COMM_WORLD.Recv(&message, 1, MPI::DOUBLE, prev_rank, message_tag);
00048 
00049         if (0 == rank) {
00050             --message;
00051             ROS_INFO("Process 0 decremented value: %f",message);
00052         }
00053 
00054         ROS_INFO("Process %d received value: %f",rank,message);
00055         MPI::COMM_WORLD.Send(&message, 1, MPI::DOUBLE, next_rank, message_tag);
00056         if (0 == message) {
00057             ROS_INFO("Process %d exiting",rank);
00058             break;
00059         }
00060     }
00061 
00062     // The last process does one extra send to process 0, which needs
00063     // to be received before the program can exit */
00064 
00065     if (0 == rank) {
00066         MPI::COMM_WORLD.Recv(&message, 1, MPI::DOUBLE, prev_rank, message_tag);
00067     }
00068     
00069     // All done
00070 
00071     MPI::Finalize();
00072     return 0;
00073 }


mpi_test
Author(s): John Hsu
autogenerated on Mon Jan 6 2014 11:27:22