I've read some similar questions to the one I'm asking but the answers don't seem complete or completely clear to me.
I'm trying to parallelize a parameter scan that requires the repeated generation of a set of random numbers. With only one thread I currently do something like this:
int main() {
//Get random number generators
typedef std::mt19937 MyRNG;
std::random_device rd;
//seed generator
MyRNG rng;
rng.seed(rd());
//make my uniform distributions for each parameter
std::uniform_real_distribution<> param1(-1,1);
std::uniform_real_distribution<> param2(-1,1);
double x,y;
//Do my scan
for (int i = 0; i < N; i++) {
x = param1(rng)
y = param2(rng)
//Do things with x and y*
}
In this way I get a new x and y for every scan. Now I want to utilize multiple cores to do this in parallel. So I turn define a function void scan()
which essentially has the same contents as my main function. I then create multiple threads and each have them run scan()
. But I'm not sure if this is thread safe using std::thread. Will my random number generation in each thread as it currently is be independent? Can I save myself time by creating my RNGs outside of my void
function? Thanks.
Aucun commentaire:
Enregistrer un commentaire