Question

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!

Was it helpful?

Solution

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?

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top