sara nj
sara nj

Reputation: 207

generating random number in a loop_C++ and arrays in loop (openmp)

I have recently learn oenmp and I have two main questions. Consider simple example:

 using namespace std;
 std::minstd_rand gen(std::random_device{}());
 std::uniform_real_distribution<double> unirnd(0, 1);
 int main(){
 double eta=something;
 double x[N],y[N];
 //initializing x[] and y[]...
 for (i=0;i<N;i++)
 {
 double z= unirnd(gen) * eta;
 x[i] = some function of x[i] and y[i] and z
 }
 }

I did as below:

using namespace std;
 std::minstd_rand gen(std::random_device{}());
 std::uniform_real_distribution<double> unirnd(0, 1);
 int main(){
 double eta=something;
 double x[N],y[N];
 //initializing x[] and y[]...
 #pragma omp parallel for
 for (i=0;i<N;i++)
     {
      double z = unirnd(gen) * eta;
      x[i] = some function of x[i] and y[i] and z
     }
     }
  1. Does above code causes data race or another problem as x and y are shared variables?
  2. Could random number which is created in the foor loop cause any problem? If yes, how can I avoid the problem?

Upvotes: 1

Views: 304

Answers (1)

Passer By
Passer By

Reputation: 21160

The code snippet have data races, but not because of x and y. The race is on the random number generator.

Data race occurs if and only if there is concurrent access to the same object (memory location) and one of the access is a write (modification).

Since access to the array subobjects of x and y are mutually exclusive, no data race occurs here. The random number generator will always mutate its state on generation, and thus is a data race.

Upvotes: 1

Related Questions