Creating and Compiling an MPI Program

From Debian Clusters
Jump to: navigation, search

Quite a few of the tutorials call for a simple MPI program, so here's one below, written in C. This is borrowed from the Bootable Cluster CD project, which I used to contribute to.

Creating the Program

Open up your favorite text editor and type the following, then save it as helloworld.c. This program uses a common paradigm where one process acts as a "server process" and the rest as "client processes". The client processes will send a message to the server process, which will then print them out along with a message of its own.

#include <stdio.h>
#include <mpi.h>

int main(int argc, char ** argv) {

	int size,rank;
	int length;
	char name[80];
	MPI_Status status;
	int i;

	MPI_Init(&argc, &argv);
	// note that argc and argv are passed by address

	MPI_Comm_rank(MPI_COMM_WORLD,&rank);
	MPI_Comm_size(MPI_COMM_WORLD,&size);
	MPI_Get_processor_name(name,&length);

	if (rank==0) {
     	// server commands
		printf("Hello MPI from the server process!\n");
		for (i=1;i<size;i++) {
			MPI_Recv(name,80,MPI_CHAR,i,999,MPI_COMM_WORLD,&status);
			printf("Hello MPI!\n");
			printf(" mesg from %d of %d on %s\n",i,size,name);
		}
	} else {
		// client commands
		MPI_Send(name,80,MPI_CHAR,0,999,MPI_COMM_WORLD);
	}

	MPI_Finalize(); 
}

Compiling

To compile an MPI program written in C, run

mpicc -o hello.out helloworld.c
  • -o hello.out is an optional command that specifies the output file name, otherwise the file is named with the default a.out

Note: mpicxx will compile C++ programs with MPI, mpif77 will compile Fortran 77 MPI programs, and mpif90 will compile Fortran 90 MPI programs.

Personal tools
Namespaces
Variants
Actions
About
services
node images
clustering
web monitoring
Toolbox