开发者

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


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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜