Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ computationaly efficient and threadsafe random function

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.

like image 647
Matt Munson Avatar asked Dec 13 '22 07:12

Matt Munson


2 Answers

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.

like image 96
Kerrek SB Avatar answered Jan 12 '23 00:01

Kerrek SB


In Linux, you can read from /dev/urandom in a nonblocking way.

like image 25
RafaelLopes Avatar answered Jan 11 '23 23:01

RafaelLopes