5

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)?
Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
Matt Joiner
  • 112,946
  • 110
  • 377
  • 526

1 Answers1

4

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)

Hasturkun
  • 35,395
  • 6
  • 71
  • 104
  • +1 for pointing to [nrand48](http://pubs.opengroup.org/onlinepubs/9699919799/functions/erand48.html) and the side note on its potential issues – jschmier Feb 02 '11 at 16:02
  • Can you explain why `nrand48` is better than `random`? – Matt Joiner Feb 21 '11 at 14:21
  • 2
    AFAICT, `random` is not inherently thread safe (The glibc implementation is, since it locks its internal state, but this may not be true of all POSIX implementations). glibc offers `random_r` which is thread safe but not portable. the only thing `nrand48` does better is thread safety, allowing you to get independent random numbers streams. the ranges are similar (`random` is `2^31 - 1`, `nrand48` is `2^31`), the period for `random` may be longer. The bottom line, IMHO, is use `nrand48` if you need thread safety, `random` otherwise. – Hasturkun Feb 21 '11 at 17:20