3

What part of this code would be logical to call in your main{} class, and what part should be used within (for instance) the constructor of a new object (what should I pass as argument(s)), and why? The question is more along the lines of, what is the best way of passing random_device variables to objects (arguments, etc)?

srand ( time ( NULL ) );
std::random_device rd;
std::mt19937 mt(rd());
std::uniform_int_distribution<int> dist(1, 10);

for (int i=0; i<40; ++i)
    std::cout << (int)dist(mt) << " ";
std::cout << endl;
staxas
  • 149
  • 12

1 Answers1

2

If you are asking how to make the pseudo random number generator object available to all classes, you can use an externally defined global variable (like std::cout), or depending on your needs, a global in anonymous namespace, or a singleton.

However the safest and easiest method I found so far is to create one instance per thread. Here's how I do it:

std::mt19937 &mt()
{
  // initialize once per thread
  thread_local static std::random_device srd;
  thread_local static std::mt19937 smt(srd());
  return smt;  
}

Now each thread has its own random number generator.

Note: for visual studio, you can try using boost's thread_specific_ptr or wrap the random_device and mersenne twister in a class and use visual c++ TLS.

nurettin
  • 11,090
  • 5
  • 65
  • 85