HP-MPI User's Guide (11th Edition)

Example applications
cart.C
Appendix A 245
cart.C
This C++ program generates a virtual topology. The class Node
represents a node in a 2-D torus. Each process is assigned a node or
nothing. Each node holds integer data, and the shift operation exchanges
the data with its neighbors. Thus, north-east-south-west shifting returns
the initial data.
#include <stdio.h>
#include <mpi.h>
#define NDIMS 2
typedef enum { NORTH, SOUTH, EAST, WEST } Direction;
// A node in 2-D torus
class Node {
private:
MPI_Comm comm;
int dims[NDIMS], coords[NDIMS];
int grank, lrank;
int data;
public:
Node(void);
~Node(void);
void profile(void);
void print(void);
void shift(Direction);
};
// A constructor
Node::Node(void)
{
int i, nnodes, periods[NDIMS];
// Create a balanced distribution
MPI_Comm_size(MPI_COMM_WORLD, &nnodes);
for (i = 0; i < NDIMS; i++) { dims[i] = 0; }
MPI_Dims_create(nnodes, NDIMS, dims);
// Establish a cartesian topology communicator
for (i = 0; i < NDIMS; i++) { periods[i] = 1; }
MPI_Cart_create(MPI_COMM_WORLD, NDIMS, dims, periods, 1,
&comm);
// Initialize the data
MPI_Comm_rank(MPI_COMM_WORLD, &grank);
if (comm == MPI_COMM_NULL) {
lrank = MPI_PROC_NULL;
data = -1;
} else {
MPI_Comm_rank(comm, &lrank);