My question is about synchronizing threads. Basically, if I have an OpenMP
code in Fortran
, each thread is doing something. There are two possibilities for synchronizing them (let some variable have the same value in each thread), I think.
- add
!$OMP BARRIER
- add
!$OMP END PARALLEL
. If necessary, add!$OMP PARALLEL
and!$OMP END PARALLEL
block later on.
Are options 1) and 2) equivalent? I saw some question about barrier
in nested threads omp barrier nested threads
So far I am more interseted in simpler scanarios with Fortran
. E.g., for the code below, if I use barrier
, it seems the two if (sum > 500) then
conditions will behave the same, at least by gfortran
.
PROGRAM test
USE OMP_LIB
integer :: numthreads, i, sum
numthreads = 2
sum = 0
call omp_set_num_threads(numthreads)
!$OMP PARALLEL
if (OMP_GET_THREAD_NUM() == 0) then
write (*,*) 'a'
do i = 1, 30
write (*,*) sum
sum = sum + i
end do
!write (*,*) 'sum', sum
else if (OMP_GET_THREAD_NUM() == 1) then
write (*,*) 'b'
do i = 1, 15
write (*,*) sum
sum = sum + i
end do
!write (*,*) 'sum', sum
end if
!$OMP BARRIER
if (sum > 500) then
write (*,*) 'sum v1'
else
write (*,*) 'not yet v1'
end if
!$OMP END PARALLEL
if (sum > 500) then
write (*,*) 'sum v2', sum
else
write (*,*) 'not yet v2', sum
end if
END
My concern is, for a code
blah1
!$OMP PARALLEL
!$OMP END PARALLEL
blah2
if the computer will execute as blah1
-> omp
-> blah2
. If the variables (e.g., the sum
in the example code) in blah2
has been evaluated completely in the omp
block, I don't need to worry if some thread in omp
goes faster, compute part of an entry (e.g., sum
in the question), and goes to the if
condition in blah2
section, leads to some unexpected result.