C ++ computational efficiency and thread safe random function

I recently found out the hard way that #<cstdlib> rand() not thread safe, and it is implemented in Linux using mutual prohibitions, which causes a bottleneck with frequent calls to rand() multiple threads. rand_r works as a replacement, but concerns the quality of random number generation. Moreover, this situation makes me wonder if there can be fast random number generators, because, apparently, my code spends a lot of time creating random numbers. There are several alternatives listed in the link above, but I'm not sure about their speed and that other alternatives may be there.

+4
source share
2 answers

If you do not need statistical control over the flows, 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; } 

Mersenne twister PRNG is fast and has good statistical properties. Maintaining a separate (and separately spent) engine object in each thread, you avoid all concurrency problems.

+11
source

On Linux, you can read / dev / urandom in a non-blocking way.

+2
source

Source: https://habr.com/ru/post/1382572/


All Articles