Search code examples
clinuxrandomposixsrand

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)?

Solution

  • 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)