Conditional change in shared variable

General OpenMP discussion
Forum rules
The OpenMP Forums are now closed to new posts. Please visit Stack Overflow if you are in need of help: https://stackoverflow.com/questions/tagged/openmp
Locked
selcukhan
Posts: 1
Joined: Tue Jan 05, 2021 1:56 am

Conditional change in shared variable

Post by selcukhan »

Dear Friends,

I have a very simple Fortran code that counts the even numbers in an array. I have defined a shared variable and I am changing it at each subprocces. I have tested shared, dynamic, reduction and also atomic keyword. But the program is not working properly.
Do you have any idea?

Here is my code

use omp_lib ! paralell processing
implicit real*4 (a-h,o-z)
implicit integer*4(i-n)
parameter(is=1000)
dimension r(is)
dimension i1(is),i2(is)

call RANDOM_NUMBER(r)
i1=int(100*r)

nnz=0
!$omp parallel do default(private) schedule(dynamic) &
!$omp shared (i1,i2,i3,nnz) ! reduction(+: nnz)
do i=1,is
if(mod(i1(i),2).eq.0) then
!omp atomic update
nnz=nnz+1
i2(nnz)=i1(i)
!omp end atomic
endif
end do
!$omp end parallel do
write(*,*) nnz
stop
end

MarkB
Posts: 808
Joined: Thu Jan 08, 2009 10:12 am
Location: EPCC, University of Edinburgh

Re: Conditional change in shared variable

Post by MarkB »

If you were just counting non-zeros, a reduction would work fine. The problem is with using nnz as an index into i2. If you don't mind the order of the values in i2 being non-deterministic, you can do this with an extra private variable and atomic capture:

Code: Select all

      nnz=0
!$omp parallel do default(private) schedule(dynamic) &
!$omp shared (i1,i2,i3,nnz) 
      do i=1,is
            if(mod(i1(i),2).eq.0) then
!$omp atomic capture
            nnz=nnz+1
            mynnz = nnz
!$omp end atomic
            i2(mynnz)=i1(i)
            endif
      end do
!$omp end parallel do


Locked