code example
MPI message passing interface
two-sided communication.
RapidMind Multi-Core Development Platform

#include <mpi.h>
#include <rapidmind/platform.hpp>
using namespace rapidmind;


int main(int argc, char *argv[]) {
  int n = ...;
  MPI_Init(&argc, &argv);
  int numproc, me;
  MPI_Comm_size(MPI_COMM_WORLD, &numproc);
  MPI_Comm_rank(MPI_COMM_WORLD, &me);
  int p_left = -1, p_right = -1;
  if (me > 0)
   p_left = me-1;
  if (me < numproc-1)
   p_right = me+1;
  int n_local0 = 1 + (me * (n-1)) / numproc;
  int n_local1 = 1 + ((me+1) * (n-1)) / numproc;
  rapidmind::init();
  // allocate only local part + ghost zone of the arrays x,y
  float *x, *y;
  Array<1, Value1f> xr(n_local1 - n_local0 + 2);
  Array<1, Value1f> yr(n_local1 - n_local0 + 2);
  x = xr.write_data();
  y = yr.write_data();
  x -= (n_local0 - 1);
  y -= (n_local0 - 1);

  ... // fill x, y

  // fill ghost zone
  MPI_Status s;
  if (p_left != -1)
    MPI_Send(&y[n_local0], 1, MPI_FLOAT, p_left,
      1, MPI_COMM_WORLD);
  if (p_right != -1) {
    MPI_Recv(&y[n_local1], 1, MPI_FLOAT, p_right,
      1, MPI_COMM_WORLD, &s);
    MPI_Send(&y[n_local1-1], 1, MPI_FLOAT, p_right,
      2, MPI_COMM_WORLD);
  }
  if (p_left != -1)
    MPI_Recv(&y[n_local0-1], 1, MPI_FLOAT, p_left,
      2, MPI_COMM_WORLD, &s);
 

  Program add3 = RM_BEGIN {
   In<Value1f> a;
   In<Value1f> b;
   In<Value1f> c;
   Out<Value1f> d;
   d = a + (b + c) * .5;
  } RM_END;
 
  Program add2 = RM_BEGIN {
   In<Value1f> a;
   In<Value1f> b;
   Out<Value1f> c;
   c = a + b;
  } RM_END;
 
  Program sqr = RM_BEGIN {
   In<Value1f> a;
   Out<Value1f> b;
   b = a * a;
  } RM_END;
 
  Array<1, Value1f> x0 = add3(slice(xr,1,n_local1-n_local0),
   offset(yr,2), take(yr,n_local1-n_local0));
  xr = x0;
  Array<1, Value1f> er = reduce(add2,
   sqr(slice(yr,1,n_local1-n_local0));
  float e = *er.read_data();

  float e_local = e;
  MPI_Allreduce(&e_local, &e, 1, MPI_FLOAT, MPI_SUM, MPI_COMM_WORLD);

  ... // output x, e

  x += (n_local0 - 1);
  y += (n_local0 - 1);
  MPI_Finalize();
  return 0;
}

[start] [references] [download] [install]