c++ randomization in parallel

96 views Asked by At

Counting pi using montecarlo method. Is there any way to make randomization same for any amounts of threads? In essence, what I am looking for is to obtain the same answer for every fixed combination of set n and seed, regardless of the number of threads I use.

double montecarlo(int n, int seed)
{
int pts = 0;
#pragma omp parallel
    {
        std::mt19937_64 rng(seed);
        std::uniform_real_distribution<double> dist(0.0, 1.0);

        #pragma omp for reduction(+:pts)
        for (int i = 0; i < n; ++i)
        {
            double x = dist(rng), y = dist(rng);
            pts += (x * x + y * y <= 1);
        }
    }

    double pi = 4.0 * pts / n;
    return pi;
}
1

There are 1 answers

4
Victor Eijkhout On
  1. Divide b=n/nthreads: that's how many iterations each thread will execute. (I'm assuming a schedule(static).)
  2. Each thread creates its own random number generator, but all with the same seed.
  3. Let thread p call the random number generator pb times.
  4. And now you start the parallel loop.

This way the threads will compute the same composite random sequence as a single thread will.

Alternatively, let each thread prime its generator by p steps, but in each iteration progress by nthreads steps.

Either way you get a composite sequence that is identical to the sequential sequence.