POSIX C API 中的随机数
我希望在 POSIX 系统上生成大的非负整数随机值。我发现了 2 个可能符合要求的函数及其各自的初始值设定项:
#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.
- 哪些函数是首选(线程安全和生成的值范围)?
- 鉴于安全性不是问题,我应该如何播种它们?
- 由于播种函数的参数不同(
long int
与unsigned int
),播种方法是否应该有所不同?
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.
- Which functions are preferred (thread-safety and range of values generated)?
- Given that security is not a concern, how should I seed them?
- Should seeding methods differ due to the differing arguments for the seeding functions (
long int
vs.unsigned int
)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用nrand48,它与lrand48具有相同的范围,并接收一个指向用作种子的数组的指针。使该线程成为本地线程将确保线程安全。 (顺便说一句,glibc 实现可能存在一些问题,请参阅 http://evanjones。 ca/random-thread-safe.html 了解更多信息,此页面还包含线程安全随机数生成函数的很好的总结)
Use
nrand48
, it has the same range aslrand48
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)