mercredi 18 mai 2016

How to generate random numbers in a thread safe way with OpenMP

Before parallelization, I was creating one default_random_engine object outside the loop since creating such objects isn't cheap. And I was reusing it inside the loop.

When parallelizing with OpenMP, I noticed that uniform_dist(engine) takes a mutable reference to the random engine which I assume isn't thread safe. The program isn't crashing but I worry about its correctness.

I assume that random_device is thread safe so I could just move the definition of default_random_engine inside the loop but I don't want to create a random engine object every iteration since I read that that isn't cheap.

I think that an other way would be to create an array (of size: the number of threads) of default_random_engine objects and use OpenMP functions to select the right object at the start of each iteration based on thread ids.

Is there a better way?

#include <iostream>
#include <random>
using namespace std;

int main() {
    int N = 1000;
    vector<int> v(N);
    random_device r;
    default_random_engine engine(r());

    #pragma omp parallel for
    for (int i = 0; i < N; ++i) {
         uniform_int_distribution<int> uniform_dist(1, 100);
         // Perform heavy calculations
         v[i] = uniform_dist(engine); // I assume this is thread unsafe
    }
    return 0;
}




Aucun commentaire:

Enregistrer un commentaire