7.9.5.  Examples

The examples were tested on Linux with the OpenMPI MPI implementation installed in a default location. The OpenMPI MPI implementation needs no special configuration to run the examples.

First, an example where the process with rank 0 broadcasts a Hello World message. All the remaining processes receive and display the message.

Example 7.1.  Broadcast Example

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include <mpi.h>

int main (int iArgC, char *apArgV [])
{
  int iRank;
  int iLength;
  char *pMessage;
  char acMessage [] = "Hello World !";

  MPI_Init (&iArgC, &apArgV);

  MPI_Comm_rank (MPI_COMM_WORLD, &iRank);

  if (iRank == 0)
  {
    iLength = sizeof (acMessage);
    MPI_Bcast (&iLength, 1, MPI_INT, 0, MPI_COMM_WORLD);
    MPI_Bcast (acMessage, iLength, MPI_CHAR, 0, MPI_COMM_WORLD);
    printf ("Process 0: Message sent\n");
  }
  else
  {
    MPI_Bcast (&iLength, 1, MPI_INT, 0, MPI_COMM_WORLD);
    pMessage = (char *) malloc (iLength);
    MPI_Bcast (pMessage, iLength, MPI_CHAR, 0, MPI_COMM_WORLD);
    printf ("Process %d: %s\n", iRank, pMessage);
  }

  MPI_Finalize ();

  return (0);
}

To compile the example, store the source in a file named Broadcast.c and use the following command:

mpicc Broadcast.c -o Broadcast

To run the example, use the following command:

mpirun -np 5 Broadcast

The -np 5 command line option tells the middleware to run the example in 5 parallel processes. The output of the example should look like this:

Process 0: Message sent
Process 3: Hello World !
Process 1: Hello World !
Process 2: Hello World !
Process 4: Hello World !

Next, an example where the processes perform a scan reduction with their rank as the input and multiplication as the operation and display the output. With rank 0 excluded from multiplication, the processes will in effect display a factorial of their rank.

Example 7.2.  Scan Example

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include <mpi.h>

int main (int iArgC, char *apArgV [])
{
  int iOutput;
  int iInput;
  int iRank;

  MPI_Init (&iArgC, &apArgV);
  MPI_Comm_rank (MPI_COMM_WORLD, &iRank);
  if (iRank == 0) iInput = 1;
             else iInput = iRank;
  MPI_Scan (&iInput, &iOutput, 1, MPI_INT, MPI_PROD, MPI_COMM_WORLD);
  printf ("Process %d: Factorial %d\n", iRank, iOutput);
  MPI_Finalize ();

  return (0);
}

To compile and run the example, use similar commands as before. The output of the example should look like this:

Process 0: Factorial 1
Process 3: Factorial 6
Process 1: Factorial 1
Process 4: Factorial 24
Process 2: Factorial 2