marcman
marcman

Reputation: 3383

Defining & seeding pseudo-random number generator with global scope (C++)

Is it dangerous/bad form to declare and seed an instance of some RNG (like std::mt19937) as a global variable? That way any function call that uses random numbers is essentially synchronized for a given seed. That is, for a given seed, my entire program will run identically. Potential bugs aside, does this also sacrifice any randomness?

Is a better alternative to do declare it in the main() and then just pass the reference to it for any subsequent use in functions?

Thanks in advance for your help!

Upvotes: 0

Views: 453

Answers (1)

Josh Kelley
Josh Kelley

Reputation: 58352

A global RNG doesn't sacrifice any randomness, but it's like using any other global variable:

  • It simplifies the initial implementation.
  • It can make future development harder. (E.g., for unit test purposes, maybe you'll want to specify a particular RNG instance with a repeatable sequence.)
  • It introduces thread safety concerns. (Two threads accessing a global RNG at the same time becomes a race condition.)

The conventional wisdom is that globals and singletons cause more problems than they solve, but you'll have to decide for yourself how the tradeoffs balance for your program.

Upvotes: 1

Related Questions