Message Passing Interface (MPI) : Hello World!

In this post, we are going to look at the hello world code for Message Passing Interface (MPI).

#include"stdio.h"
#include"mpi.h"

int main(int argc, char **argv)
{
	int myid, size;
	
	//Initialize MPI environment 
	MPI_Init(&argc,&argv);
	
	//Get total number of processes
	MPI_Comm_size(MPI_COMM_WORLD, &size);
	
	//Get my unique ID among all processes
	MPI_Comm_rank(MPI_COMM_WORLD, &myid);
	
	printf("Hello World from %d out of %d.\n",myid, size);
	
	//End MPI environment        
	MPI_Finalize();
}

To compile this code, use following command –

mpicc hello_world.c

To execute this code, run following command –

mpiexec -n 4 ./a.out

This command creates 4 processes. Each of this process, executes the same “a.out” file. For 4 processes, one will get output something similar to following output. Please note that the order in which different processes are calling their “printf” can vary.

Hello World from 0 out of 4.
Hello World from 1 out of 4.
Hello World from 2 out of 4.
Hello World from 3 out of 4.