The following examples show how to use the OpenMP* features.
This example shows a simple parallel loop where each iteration contains a different number of instructions. To get good load balancing, dynamic scheduling is used. The end do has a nowait because there is an implicit barrier at the end of the parallel region.
Example |
---|
subroutine do_1 (a,b,n) real a(n,n), b(n,n) !$OMP PARALLEL !$OMP& SHARED(A,B,N) !$OMP& PRIVATE(I,J) !$OMP DO SCHEDULE(DYNAMIC,1) do i = 2, n do j = 1, i b(j,i) = ( a(j,i) + a(j,i-1) ) / 2 enddo enddo !$OMP END DO NOWAIT !$OMP END PARALLEL end |
This example shows two parallel regions fused to reduce fork/join overhead. The first end do has a nowait because all the data used in the second loop is different than all the data used in the first loop.
Example |
---|
subroutine do_2 (a,b,c,d,m,n) real a(n,n), b(n,n), c(m,m), d(m,m) !$OMP PARALLEL !$OMP& SHARED(A,B,C,D,M,N) !$OMP& PRIVATE(I,J) !$OMP DO SCHEDULE(DYNAMIC,1) do i = 2, n do j = 1, i b(j,i) = ( a(j,i) + a(j,i-1) ) / 2 enddo enddo !$OMP END DO NOWAIT !$OMP DO SCHEDULE(DYNAMIC,1) do i = 2, m do j = 1, i d(j,i) = ( c(j,i) + c(j,i-1) ) / 2 enddo enddo !$OMP END DO NOWAIT !$OMP END PARALLEL end |
This example demonstrates the use of the SECTIONS directive. The logic is identical to the preceding DO example, but uses SECTIONS instead of DO. Here the speedup is limited to 2 because there are only two units of work whereas in DO: Two Difference Operators above there are n-1 + m-1 units of work.
Example |
---|
subroutine sections_1 (a,b,c,d,m,n) real a(n,n), b(n,n), c(m,m), d(m,m) !$OMP PARALLEL !$OMP& SHARED(A,B,C,D,M,N) !$OMP& PRIVATE(I,J) !$OMP SECTIONS !$OMP SECTION do i = 2, n do j = 1, i b(j,i)=( a(j,i) + a(j,i-1) ) / 2 enddo enddo !$OMP SECTION do i = 2, m do j = 1, i d(j,i)=( c(j,i) + c(j,i-1) ) / 2 enddo enddo !$OMP END SECTIONS NOWAIT !$OMP END PARALLEL end |
This example demonstrates how to use a SINGLE construct to update an element of the shared array a. The optional nowait after the first loop is omitted because it is necessary to wait at the end of the loop before proceeding into the SINGLE construct.
Example |
---|
subroutine sp_1a (a,b,n) real a(n), b(n) !$OMP PARALLEL !$OMP& SHARED(A,B,N) !$OMP& PRIVATE(I) !$OMP DO do i = 1, n a(i) = 1.0 / a(i) enddo !$OMP SINGLE a(1) = min( a(1), 1.0 ) !$OMP END SINGLE !$OMP DO do i = 1, n b(i) = b(i) / a(i) enddo !$OMP END DO NOWAIT !$OMP END PARALLEL end |
See more examples in the OpenMP Fortran version 2.5 specifications (http://www.openmp.org/specs).