Hello World MPI C Source Code

Got something interesting, MPI (Message Passing Interface) is the language or library which needed to create parallel programming. So let’s start with the usual way to begin code, “Hello World”. This post will be show how to make the simplest MPI code in C language.

#include "stdio.h"
#include "mpi.h"
 
int main(int argc, char** argv)
{
    int rank;
    int size;
 
    /* Initialize MPI  */
    MPI_Init(&argc, &argv);
 
    /* Getting the World Size and Process Number (rank) */
    MPI_Comm_size(MPI_COMM_WORLD, &size);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
 
    /* Routine for process 0 */
    if (rank == 0)
    {
        printf("P%d : I Found this world size is %d processesn", rank, size);
        printf("P%d : Hello World! This is process number %d writing!n", rank, rank);
    }
    /* Routine for process 1 */
    else if (rank == 1)
    {
        printf("P%d : I Found this world size is %d processesn", rank, size);
        printf("P%d : Hello World! This is process number %d writing!n", rank, rank);
    }
    /* Routine for Other Processes */
    else
    {
        printf("P%d : I'm Unused Process...n", rank);
    }
 
    /* End of MPI */
    MPI_Finalize();
    return 0;
}

Then how to compile it and run? The answer is you must have a GRID Cluster, for starting you can visit my other site http://web.imkrisna.com/course/grid/mpich2-ubuntu-lucid.html (in Indonesian, please use Google Translate if you’re not Indonesian) And the result with 4 process is something like below (the order of output may be different for each execution)

P0 : I Found this world size is 4 processes
P0 : Hello World! This is process number 0 writing!
P2 : I'm Unused Process...
P3 : I'm Unused Process...
P1 : I Found this world size is 4 processes
P1 : Hello World! This is process number 1 writing!

Leave a Reply

Your email address will not be published. Required fields are marked *

Post Navigation