MPI hello.f90

Obligatory Hello, World! program built with MPI in Fortran.

This example requires fortran, so if you don't have it installed already, install gfortran from the ubuntu repositories.

Every MPI program should call a minimum of two functions: MPI_INIT() and MPI_FINALIZE(). The example below is a very simple Hello, World! Fortran program:

program hello

  use mpi
  implicit none

  integer:: error, rank, size

  call MPI_INIT(error)

  write(*,*) "Hello, World!"
  
  Call MPI_FINALIZE(error)

end program hello

MPI programs can be compiled with the appropriate calls to MPI wrapper scripts, if they exist. For OpenMPI, this is called 'mpif90'. The resulting executable can then be run using the 'mpiexec' or 'mpirun' commands. Take care to use the 'mpiexec' command from the same implementation as the build.

george@nano:~/MPI$ mpif90 -o hello hello.f90 
george@nano:~/MPI$ mpiexec -n 4 hello
 Hello, World!
 Hello, World!
 Hello, World!
 Hello, World!
george@nano:~/MPI$ mpiexec -host nano01,nano02,nano03,nano04 -n 4 hello
 Hello, World!
 Hello, World!
 Hello, World!
 Hello, World!

Each process in an MPI application is able to identify itself by a unique rank, and can query for both rank and total number of processes:

program hello

  use mpi
  implicit none

  integer:: error, rank, size

  call MPI_INIT(error)

  call MPI_COMM_SIZE(MPI_COMM_WORLD, size, error)
  call MPI_COMM_RANK(MPI_COMM_WORLD, rank, error)
  
  write(*,*) "Hello, World!  I am rank ",rank," of ",size," processes"
  
  Call MPI_FINALIZE(error)

end program hello

Last updated