How do I generate thread-safe uniform random numbers? How do I generate thread-safe uniform random numbers? multithreading multithreading

How do I generate thread-safe uniform random numbers?


Have you tried this?

int intRand(const int & min, const int & max) {    static thread_local std::mt19937 generator;    std::uniform_int_distribution<int> distribution(min,max);    return distribution(generator);}

Distributions are extremely cheap (they will be completely inlined by the optimiser so that the only remaining overhead is the actual random number rescaling). Don’t be afraid to regenerate them as often as you need – in fact, resetting them would conceptually be no cheaper (which is why that operation doesn’t exist).

The actual random number generator, on the other hand, is a heavy-weight object carrying a lot of state and requiring quite some time to be constructed, so that should only be initialised once per thread (or even across threads, but then you’d need to synchronise access which is more costly in the long run).


Make the generator static, so it's only created once. This is more efficient, since good generators typically have a large internal state; more importantly, it means you are actually getting the pseudo-random sequence it generates, not the (much less random) initial values of separate sequences.

Create a new distribution each time; these are typically lightweight objects with little state, especially one as simple as uniform_int_distribution.

For thread safety, options are to make the generator thread_local, with a different seed for each thread, or to guard it with a mutex. The former is likely to be faster, especially if there's a lot of contention, but will consume more memory.


You can use one default_random_engine per thread using Thread Local Storage.

I can not tell you how to correctly use TLS since it is OS dependent. The best source you can use is to search through the internet.