Scientific Computing & Visualization
Help Contact
About Accounts Computation Visualization Documentation Services

Multiprocessing by Message Passing MPI

Example 1.1 Integration with MPI Blocking Send/Receive

This example demonstrates parallel integration (see Example 1 for detail) via the following MPI library routines. Click on them for details:

#include <mpi.h>
#include <math.h>
#include <stdio.h>
float fct(float x)
{
      return cos(x);
}
/* Prototype */
float integral(float a, int i, float h, int n);
void main(int argc, char* argv[])
{
/***********************************************************************
 *
 * This is one of the MPI versions on the integration example
 * It demonstrates the use of :
 *
 * MPI_Init
 * MPI_Comm_rank
 * MPI_Comm_size
 * MPI_Recv
 * MPI_Send
 * MPI_Finalize
 *
 * Dr. Kadin Tseng
 * Scientific Computing and Visualization
 * Boston University
 * 1998
 *
 ***********************************************************************/
      int n, p;
      float h, result, a, b, pi;

      int myid, src, dest, tag;
      MPI_Status status;
      float my_result;

/* Starts MPI processes ... */

      MPI_Init(&argc,&argv);                 /* starts MPI */
      MPI_Comm_rank(MPI_COMM_WORLD, &myid);  /* get current process id */
      MPI_Comm_size(MPI_COMM_WORLD, &p);     /* get number of processes */


      pi = acos(-1.0);  /* = 3.14159... */
      a = 0.;           /* lower limit of integration */
      b = pi*1./2.;     /* upper limit of integration */
      n = 500;          /* number of increment within each process */

      dest = 0;         /* define the process that computes the final result */
      tag = 123;        /* set the tag to identify this particular job */

      h = (b-a)/n/p;    /* length of increment */

      my_result = integral(a,myid,h,n);

      printf("Process %d has the partial result of %f\n", myid,my_result);
  
      if(myid == 0) {
        result = my_result;
        for (src=1;src<p;src++) {
          MPI_Recv(&my_result, 1, MPI_REAL, src, tag,
                        MPI_COMM_WORLD, &status);  /* not safe */
          result += my_result;
        }
        printf("The result =%f\n",result);
      }
      else
        MPI_Send(&my_result, 1, MPI_REAL, dest, tag,
                      MPI_COMM_WORLD);      /* send my_result to intended dest. */
      MPI_Finalize();                       /* let MPI finish up ... */
}
float integral(float a, int i, float h, int n)
{
      int j;
      float h2, aij, integ;

      integ = 0.0;                 /* initialize integral */
      h2 = h/2.;
      for (j=0;j<n;j++) {             /* sum over all "j" integrals */
        aij = a + (i*n + j)*h;        /* lower limit of "j" integral */
        integ += fct(aij+h2)*h;
      }  
      return integ;
}
Boston University
Boston University
 
OIT | CCS | July 2, 2008  
Scientific Computing & Visualization Boston University home page Boston University home page