Does the c standard provide a thread safe random number generator where instead of using a global state the generator uses and modifies the provided state buffer ? I'm familiar with drand48_r and rand_r but on the documentation it is said that rand_r is a weak random number generator and drand48_r is obsolete. What would be a good thread safe random number generator ? I need one for double and one for int/long type. Also it would be great if it's portable.
Asked
Active
Viewed 446 times
3
-
2The only random number generator provided by the C standard is `rand()`, and it's not thread safe. `rand_r`, `random_*`, `drand48_*` are specified by POSIX but not ISO C. The quality of the numbers generated by any of them is up to your implementation. If it's not good enough, there are many many third-party libraries. – Nate Eldredge Jul 19 '20 at 19:07
-
Can you mention some of those third party libraries ? – Moshiur Rahman Jul 19 '20 at 19:08
-
1There are lots of examples discussed at https://stackoverflow.com/questions/822323/how-to-generate-a-random-int-in-c. Mersenne Twister is one that many people like, perhaps mainly due to its catchy name; I can't speak to its quality or performance. – Nate Eldredge Jul 19 '20 at 19:12
-
Thanks a lot. I'll check these libraries and if I dont find any good thread safe generator I'll just use the source code of rand() from glibc and edit it to make it use the provided state buffer. – Moshiur Rahman Jul 19 '20 at 19:23
-
For Linux 5.17, there are many changes to the quality and speed random number generation. Good general write-up [New Linux kernel bolsters random number generation](https://www.theregister.com/2022/03/21/new_linux_kernel_has_improved/) and [Random number generator updates for Linux 5.17](https://brianlovin.com/hn/29840388) – David C. Rankin Apr 15 '22 at 04:22
1 Answers
1
C17 defines the random functions rand()
(7.22.2.1) and srand()
(7.22.2.2). Neither are required to avoid data races.

Allan Wind
- 23,068
- 5
- 28
- 38