1

I am new to openMP, in my program complex simulations are needed, to repeat the result, the seed is set for each simulation, however, when implementing openMP, different results are produced for each time I run it. so I write a simple example to check the problem as follows, I also generated different result each time:

#include <iostream>
#include <omp.h>
using namespace std;


int main () {

double A[10];

#pragma omp parallel for
for( int i=0;i<10;i++){
    srand(i+1);
    int m = rand()%100;
    A[i] = m;
}

cout<<"A= \n";

for(int i=0;i<10;i++){
    cout<<i<<" "<<A[i]<<" \n";
}
   return 0;
}

I run it twice, the results are: A= 0 86 1 25 2 78 3 1 4 46 5 95 6 77 7 83 8 15 9 8

and A= 0 15 1 41 2 65 3 1 4 75 5 85 6 95 7 83 8 74 9 8

Thank you very much!

user3159019
  • 33
  • 1
  • 5

2 Answers2

2

rand() uses static state and is not threadsafe. You'll need to use a different, thread-safe, PRNG. See Thread-safe random number generation for Monte-Carlo integration or Do PRNG need to be thread safe?

Community
  • 1
  • 1
pburka
  • 1,434
  • 9
  • 12
1

This is a bug

A[i] += m;

You're reading the prior value of A[i] which has never been assigned. That's undefined behavior. try

A[i] = m;

Then, note that the random number state might not be threadlocal. Get a better RNG, where you have an explicit state variable instead of accessing shared global state.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
  • Thanks, it is indeed a problem, but even I change it, the problems still exist. if I remove "#pragma omp parallel for", I can get the same result, but if I add that line, the result is different each time. more, I am not quite understand your last comments about RNG, would you mind explaining it more clearly? Thank you very much! – user3159019 Jan 04 '14 at 19:35
  • @user3159019: Many RNG (random number generators) are implemented as objects, and use member variables to store the seed/state instead of globals. You need to have separate state for each thread, and the easiest way is for each thread to use its own RNG object. The new C++11 standard defines a bunch of RNG classes. – Ben Voigt Jan 04 '14 at 19:40
  • See http://stackoverflow.com/questions/7114043/random-number-generation-in-c11-how-to-generate-how-do-they-work – Ben Voigt Jan 04 '14 at 19:41