Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random numbers in POSIX C API

I'm looking to generate large, non-negative integer random values on a POSIX system. I've found 2 possible functions that fit the bill, and their respective initializers:

       #include <stdlib.h>

       long int random(void);    
       void srandom(unsigned int seed);
CONFORMING TO
       4.3BSD, POSIX.1-2001.

       // and

       long int lrand48(void);
       void srand48(long int seedval);    
CONFORMING TO
       SVr4, POSIX.1-2001.
  1. Which functions are preferred (thread-safety and range of values generated)?
  2. Given that security is not a concern, how should I seed them?
  3. Should seeding methods differ due to the differing arguments for the seeding functions (long int vs. unsigned int)?
like image 292
Matt Joiner Avatar asked Oct 14 '22 17:10

Matt Joiner


1 Answers

Use nrand48, it has the same range as lrand48 and receives a pointer to an array used as a seed. making this thread local will ensure thread safety. (as a side note, it appears the glibc implementation may have some issues, see http://evanjones.ca/random-thread-safe.html for more information, this page also contains a nice summary of thread safe random number generation functions)

like image 137
Hasturkun Avatar answered Nov 18 '22 03:11

Hasturkun