# Trying to make a program using OpenMP give same output as non parallel counterpart

**URL:** <https://fortran-lang.discourse.group/t/trying-to-make-a-program-using-openmp-give-same-output-as-non-parallel-counterpart/3410>\
**Category:** Help\
**Created:** [May 8, 2022, 5:43pm UTC](https://fortran-lang.discourse.group/t/trying-to-make-a-program-using-openmp-give-same-output-as-non-parallel-counterpart/3410 "2022-05-08T17:43:02Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![JohnCampbell](https://avatars.discourse-cdn.com/v4/letter/j/5daacb/32.png) [@JohnCampbell](https://fortran-lang.discourse.group/u/JohnCampbell)\
**Post date:** [May 9, 2022, 4:40am UTC](https://fortran-lang.discourse.group/t/trying-to-make-a-program-using-openmp-give-same-output-as-non-parallel-counterpart/3410/2 "2022-05-09T04:40:08Z")

</div>

> [@Aurelius\_Nero](#):
>
> ```auto
> !$OMP PARALLEL SHARED(k,arr)
> !$OMP DO
> do i=1,n
> do j=1,n
> arr(k)%x=val(i)
> arr(k)%y=val(j)
> k=k+1
> end do
> end do
> !$OMP END DO
> !$OMP END PARALLEL
> 
> ```

The use of k = k+1 will not work as required in this code, as the initial value of k is not adjusted for each thread (based on the value “i”). “k” can not be shared and must be private.  
You could try either of the following, which should be identical with most optimising compilers

```auto
! explicit definition of k
 !$OMP PARALLEL DO SHARED(arr,val,n) PRIVATE(i,j,k) SCHEDULE(STATIC)
  do i=1,n
     do j=1,n
        k = (i-1)*n+j
        arr(k)%x=val(i)
        arr(k)%y=val(j)
     end do
  end do
  !$OMP END PARALLEL DO

! incremental version of k
 !$OMP PARALLEL DO SHARED(arr,val,n) PRIVATE(i,j,k) SCHEDULE(STATIC)
  do i=1,n
     k = (i-1)*n + 1
     do j=1,n
        arr(k)%x=val(i)
        arr(k)%y=val(j)
        k = k+1
     end do
  end do
  !$OMP END PARALLEL DO

```

This approach applies PARALLEL DO to the DO i loop.  
It is unlikely this will improve performance as there is “low arithmetic intensity” [https://fortran-lang.discourse.group/t/compiling-only-part-of-code-with-ffast-math/3196/28](https://fortran-lang.discourse.group/t/compiling-only-part-of-code-with-ffast-math/3196/28)

---

_[View the full topic](https://fortran-lang.discourse.group/t/trying-to-make-a-program-using-openmp-give-same-output-as-non-parallel-counterpart/3410)._
