views:

47

answers:

0

I would like to parallelize my boost random number generator code in C++ with OpenMP. I'd like to do it in way that is both efficient and thread safe. Can someone give me pointers on how this is done? I am currently enclosing what I have below; this is clearly not thread safe since the static variable in the sampleNormal function is likely to give a race condition. The number of samples (nsamples) is much bigger than n.

#pragma omp parallel for private(i,j) 
for (i = 0; i < nsamples; i++) {
   for (j = 0; j < n; j++) {
      randomMatrix[i + nsamples*j] = SampleNormal(0.0, 1.0);
   }
}

double SampleNormal (double mean, double sigma)
{
  // Create a Mersenne twister random number generator
  static mt19937 rng(static_cast<unsigned> (std::time(0)));
  // select Gaussian probability distribution
  normal_distribution<double> norm_dist(mean, sigma);
  // bind random number generator to distribution
  variate_generator<mt19937&, normal_distribution<double> >  normal_sampler(rng, norm_dist);
  // sample from the distribution
  return normal_sampler();
}