Parallel computation of Do loop using Openmpi in Fortran

2022-01-23
#Fortran

1. Key command

use omp_lib

!$OMP PARALLEL 
!$OMP DO

!$OMP END DO
!$OMP END PARALLEL 

or

use omp_lib

!$OMP PARALLEL DO

!$OMP END PARALLEL DO

2. File

The content of the file test.f90 is:

program main

    use omp_lib
    implicit integer (i-n)
    implicit real*8 (a-h,o-z)

    real(8),allocatable:: number(:,:)

    inumber=2
    jnumber=3
    allocate(number(inumber,jnumber))

    write(*,*) "parallel do"

    call cpu_time(time_begin1)
    !$OMP PARALLEL DO
    do i=1,inumber
        do j=1,jnumber
            number(i,j)=i+j
            write(*,*) i,j,number(i,j), OMP_get_thread_num()
        enddo
    enddo
    !$OMP END PARALLEL DO
    call cpu_time(time_end1)
    write(*,*) "The time cost is",time_end1-time_begin1

    do i=1,inumber
        do j=1,jnumber
            write(*,*) i,j,number(i,j)
        enddo
    enddo

    deallocate(number)

end program main

The content of the file job.sh is:

ifort -fopenmp test.f90 -o test &&
./test

or

mpif90 test.f90 -o test &&
mpirun -np 2 test

Run the command:

sh job.sh

In macOS, this command should be applied:

ifort -L/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/lib -fopenmp test.f90 -o test &&
./test

2. Reference