numerical result is changed by compiling fortran code with "-openmp"

numerical result is changed by compiling fortran code with "-openmp"


I am writting a Monte Carlo code to simulate particle collisions,

and I use my own random number genertoion subroutine in my code.

Before I parallelize the code, the simulation result can be exactly reproduced if i use the same seed number.

(all the numerical results are exactly the same).

If I compile the code with a flag (-openmp), the numerical results are changed even if I do nothing to the code.

Does anyone know how it happens and how can I avoid this problem?

Thank you.


4 posts / 0 new
Last post
For more complete information about compiler optimizations, see our Optimization Notice.

One thing that -openmp does is cause all local variables to be "automatic", that is, allocated on the stack. If you have any variables that are not initialized, they will have "random" values when you run the program. Make sure all your variables are initialized.

Retired 12/31/2016

Various problems could be incurred by using a serial pseudo-random number generator in a threaded parallel region. If you keep your random number generator in serial regions and observe precautions which Steve mentioned, you have a reasonable chance of reproducing the previous results.

There are two issues relating to your code and multi-threaded programming:

1) If all threads are using the same pseudo RNG (same sequence of numbers in same pecking order by arbitrary pecking by arbitrary threads), then the "next RNG" must be coded thread-safe. Typically this is by way of a critical section or possibly a CAS / DCAS type of operation. Failure to do so will either messup the sequence or result in multiple threads observing the same RNG at the (approximate) same time.

2) Considering 1 above, while the sequencing of the (thread safe) RNG will be the same, the individual threads pecking order will be non-determinstic. IOW each run may produce different sequences as observed by individal threads.

To correct for this (assuming this is your desire), partition the problem domain into work units for each thread, sequentially generate the random numbers per partiton (i.e. build table of random numbers for each partition), then run the code in parallel with each thread drawing on their own pre-produced random numbers.

Jim Dempsey

Leave a Comment

Please sign in to add a comment. Not a member? Join today