I recently learned the hard way that #<cstdlib> rand()
is not thread safe, and on Linux is implemented with mutexes, causing a bottleneck when rand()
is called frequently by multiple threads. rand_r
works as a replacement, but there are concerns about the quality of random number generation. Moreover, this situation has caused me to question whether there might be faster random number generators out there, since apparently my code spends a lot of time generating random numbers. There are a few alternatives listed in the link above, but I'm unsure as to their speed and to what other alternatives might be out there.
If you don't need any statistical control across threads, just use the facilities provided by <random>
:
#include <random>
typedef std:::mt19937 rng_type;
std::uniform_int_distribution<rng_type::result_type> udist(0, 200);
int main() // this can be per thread!
{
rng_type rng;
// seed rng first:
rng_type::result_type const seedval = get_seed();
rng.seed(seedval);
rng_type::result_type random_number = udist(rng);
return random_number;
}
The Mersenne twister PRNG is both fast and has good statistical properties. Maintaining a separate (and separately seeded) engine object in each thread you avoid all concurrency issues.
In Linux, you can read from /dev/urandom in a nonblocking way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With