Search code examples
c++c++11prng

best practice/idiom in random number generator usage in libraries


Suppose I am writing a library that uses C++11's prng features. Should each function/object/file in the library initialize its own random number generator? I was going to go with initializing one static std::mt19937 in the namespace and using only that one after that, but the code would be less modular. Is this recommended?


Solution

  • It's not thread-safe, so if you're going to be spawning multiple threads, make more instances of the MT19937 prng. Otherwise, it's totally up to you. Any answer here beyond that is going to be primarily opinion-based.

    If you're not memory-constrained, why try to optimize something so trivial as the number of instances of your prng out of the application? Simple answer: do what makes your program easiest to write, debug, and manage.

    A possible solution would be holding a reference to the MT19937 in each object and controlling access to it through a locking construct to make it thread-safe.