5.5 Parallel Computing 135
cout <<"Hello world, I have rank "<< my_rank <<" out of "<< numprocs << endl;
// End MPI
MPI_Finalize ();
return0;
}
The corresponding Fortran program reads
PROGRAMhello
INCLUDE"mpif.h"
INTEGER:: numprocs, my_rank, ierr
CALLMPI_INIT(ierr)
CALLMPI_COMM_SIZE(MPI_COMM_WORLD, numprocs, ierr)
CALLMPI_COMM_RANK(MPI_COMM_WORLD, my_rank, ierr)
WRITE(,)"Hello world, I've rank ",my_rank," out of ",numprocs
CALLMPI_FINALIZE(ierr)
END PROGRAMhello
MPI is a message-passing library where all the routines havea corresponding C++-bindings^3
MPI_Command_nameor Fortran-bindings (function names are by convention in uppercase, but can
also be in lower case)MPI_COMMAND_NAME
To use the MPI library you must include header files which contain definitions and decla-
rations that are needed by the MPI library routines. The following line must appear at the top
of any source code file that will make an MPI call. For Fortran you must put in the beginning
of your program the declaration
INCLUDE'mpif.h'
while for C++ you need to include the statement
#include"mpi.h"
These header files contain the declarations of functions, variabels etc. needed by the MPI
library.
The first MPI call must beMPI_INIT, which initializes the message passing routines, as
defined in for example
INTEGER:: ierr
CALLMPI_INIT(ierr)
for the Fortran example. The variableierris an integer which holds an error code when
the call returns. The value ofierris however of little use since, by default, MPI aborts the
program when it encounters an error. However,ierrmust be included when MPI starts. For
the C++ code we have the call to the function
MPI_Init(intargc, charargv)
whereargcandargvare arguments passed to main. MPI does not use these arguments in any
way, however, and in MPI-2 implementations, NULL may be passed instead. When you have
finished you must call the functionMPI_Finalize. In Fortran you use the statement
CALLMPI_FINALIZE(ierr)
(^3) The C++ bindings used in practice are the same as the C bindings, although reading older texts like [15–17]
one finds extensive discussions on the difference between C and C++ bindings. Throughout this text we will
use the C bindings.