https://gcc.gnu.org/bugzilla/show_bug.cgi?id=108336

            Bug ID: 108336
           Summary: Repeatable random_numbers with openmp
           Product: gcc
           Version: 11.3.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: fortran
          Assignee: unassigned at gcc dot gnu.org
          Reporter: gareth.davies.ga.code at gmail dot com
  Target Milestone: ---

The aim is to get repeatable random numbers with openmp. This report was
derived from a discussion including input from gfortran developer Steve Kargl:
https://fortran-lang.discourse.group/t/replicable-monte-carlo-simulation-with-openmp/4972/19

AFAIK the following program should give repeatable random numbers using openmp.
But it doesn't - there are occasional changes in results, suggestive of a race
condition. 


$ gfortran --version
GNU Fortran (Ubuntu 11.3.0-1ubuntu1~22.04) 11.3.0
Copyright (C) 2021 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

$ cat random_number7.f90 
program main
   use omp_lib
   implicit none
   integer :: n1, i, n, nt
   real :: x1, x2
   real, allocatable :: threadval(:)

   n1 = 2

   ! Initialize the master state to a repeatable sequence.
   call random_init(.true., .false.)

   ! Store final random number on each thread
!$omp parallel
   nt = omp_get_num_threads()
!$omp end parallel
   allocate(threadval(nt))
   threadval = -1.0

!$omp parallel private(x1, x2, i), shared(n1, threadval)

   ! Trigger non-master threads to get their unique seed
   if(omp_get_thread_num() /= 0) call random_number(x1)
!$omp barrier
   ! Get some random numbers -- almost repeatable (but not)
!$omp do
   do i = 1, n1
      call random_number(x1)
      call random_number(x2)
   end do
!$omp end do
   ! Store final RN on each thread
   threadval(omp_get_thread_num()+1) = x2 

!$omp end parallel

   print*, minval(threadval), maxval(threadval)
end program

$ gfortran -fopenmp random_number7.f90 -o random_number7
$ for i in {1..10}; do OMP_NUM_THREADS=6 ./random_number7; done
  0.191325366      0.876643896    
  0.191325366      0.480524838    
  0.191325366      0.876643896    
  0.191325366      0.804360509    
  0.191325366      0.804360509    
  0.191325366      0.480524838    
  0.191325366      0.670394361    
  0.191325366      0.804360509    
  0.157898605      0.191325366    
  0.191325366      0.670394361

Reply via email to