I'm using the new random number generators in in C++11. Although there are varying opinions, from this thread it seems that the majority believe they are not thread safe. As a consequence, I would like to make a program, where each thread uses its own RNG.
An example is given in the related discussion of how to accomplish this with OpenMP:
#include <random>
#include <iostream>
#include <time.h>
#include "omp.h"
using namespace std;
int main()
{
unsigned long long app = 0;
{
//mt19937_64 engine((omp_get_thread_num() + 1)); //USE FOR MULTITHREADING
mt19937_64 engine; //USE FOR SINGLE THREAD
uniform_real_distribution<double> zeroToOne(0.0, 1.0);
//#pragma omp parallel for reduction(+:app) //USE FOR MULTITHREADING
for (unsigned long long i = 0; i < 2000000000; i++)
{
if(zeroToOne(engine) < 0.5) app++;
}
}
cout << app << endl;
return 0;
}
When I run the multi-threaded and single-threaded version of this program and keep track of the time, they take the same amount of time to finish after execution. Also, app
does not have the same size in the two cases, but I suspect that is merely because of the different seeds.
Question: Does the provided example correctly show how to force each thread to use its own RNG? If not, can I see an example of how this is done, or get a reference to some place where they explain how to achieve this?