2

How does random_number() works in parallel with OpenMP?

If I run my program without parallelization I always get the same result, but with parallelization I get different (but similar) results every time.

mattiav27
  • 655
  • 2
  • 9
  • 27
  • 1
    Unless things have changed this is not specified by the standard, you will have to look at the documentation for the specific version of your compiler. But if you really care about random numbers I would use a thread safe library. I'm not an expert here but https://stackoverflow.com/questions/3772100/thread-safe-random-number-generation-for-monte-carlo-integration might be useful – Ian Bush Feb 05 '20 at 12:40

2 Answers2

5

There is no guarantee about thread safety or threading performance about random_number in general. The Fortran standard does not know OpenMP at all.

Individual compilers may offer you some guarantees, but they will be only valid for the version present in the particular compiler. For example, the current gfortran version supplies a thread-safe random number generator and "Note that in a multi-threaded program (e.g. using OpenMP directives), each thread will have its own random number state." Other compilers may differ. Notably, the compiler your user may want to use may differ and you may not know about that.

There are dedicated parallel random number generators available. For example, I use a modified version of the library that uses the Ziggurat method for several random number distributions, was parallelized by Gib Bogle and I added the implementation of xoroshiro128+ as the underlying algorithm, similar to the one used by Gfortran. There are other implementations of similar algorithms available and standard C++ contains some new generators which are actually defined to use a specific algorithm, so you could call them.

0

If your goal is to have a reproducible random numbers, take a look at this answer: https://stackoverflow.com/a/52884455/12845922

It's in C, but gives you an effective way to get reproducible results for any number of threads that could easily be converted to Fortan.

NickB
  • 113
  • 5