title: Understanding the correct use of !$omp parallel do reduction(...)
body: <p>I am trying to write a program that counts the number of primes between 1 and some number <code>n</code> in Fortran 90 utilizing OpenMP. The nested loop just counts the numbers that are not prime. I want to use an <code>omp parallel do</code> to speed this up. As far as I understand, since I am just counting numbers that are not prime, it is appropriate to just use something like <code>!$omp parallel do reduction(+:not_primes)</code>. When I run the code below in serial without the <code>!$omp lines</code> I get the following output </p>
  
  <pre><code> Primes:        5134
   OpenMP time elapsed  0.49368596076965332  
  </code></pre>
  
  <p>but when I include the !$omp lines I get </p>
  
  <pre><code> Primes: -1606400834
   OpenMP time elapsed  0.37933206558227539 
  </code></pre>
  
  <p>Have I used the <code>parallel do</code> correctly here? (apparently not, but why?) Thanks!</p>
  
  <pre><code>program prime_counter
  
  integer n, not_primes, i, j
  real*8 :: ostart,oend, omp_get_wtime
  
  ostart = omp_get_wtime()
  n=50000
  
  !$omp parallel do reduction(+:not_primes)
  do i=2,n
      do j=2,i-1
          if(mod(i,j)==0) then
              not_primes= not_primes+1
              exit
          end if
      end do
  end do
  !$omp end parallel do
  
  
  print*, 'Primes:', n-not_primes
  oend = omp_get_wtime()
  write(*,*) 'OpenMP time elapsed', oend-ostart
  
  end program
  </code></pre>