随机数和多次下注 [英] random numbers and multiple srand calls

查看:131
本文介绍了随机数和多次下注的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个程序,该程序将在循环中生成大量随机数.我正在尝试使数字的可预测性有所降低(不仅出于安全性考虑,而且还避免了多个线程之间的冲突).

I'm writing a program that will generate numerous random numbers in loops. I'm trying to make the numbers somewhat less predictable (not only for security, but to avoid collisions on multiple threads).

我注意到许多文档建议仅在程序中调用一次srand.例如: C中的随机数,选择的答案是一般来说,仅呼叫srand()放在您的程序中".

I've noticed that many documents recommended calling srand only once in the program. For example: Random numbers in C, the selected answer is "As a general rule, only call srand() once in your program".

但是为什么呢?做这样的事情为什么会那么糟糕:

But why? Why would it be so bad to do something like this:

int THIS_THREAD_SEED;
int randomness() {
    ++THIS_THREAD_SEED;
    int i;
    for(i=0 i<1000; i++) {
        unsigned n = rand_r(&THIS_THREAD_SEED) / RAND_MAX;
        /* do something with n */
    }
    return 0;
}

int do_something() {
    int i;
    for(i=0; i<1000; i++) {
        randomness();
    }
}

这样,种子会在每个函数调用中更改一次,而不是在每个程序中更改一次.这样,无论正在运行多少个线程,都不会有两个线程都具有相同的随机数列表...对吧?

As such, the seed changes once per function call, not once per program. This way, no matter how many threads are running, no two threads will every have the same random number list... Right?

更新 假设我或者每个线程都有一个唯一的种子,或者在全局SEED上使用互斥以防止出现竞争情况.

UPDATE Assume I either have a unique seed for each thread, or mutex on a global SEED to prevent race conditions.

推荐答案

让我们将这个问题分为两个单独的问题.

let's break this question into two separate ones.

  1. 如果您在访问随机数生成器时担心竞争状况,请创建一个互斥量或其他同步原语来避免这种情况.

  1. if you worry about race conditions when accessing random number generator, create a mutex or other synchronization primitive to avoid this.

如果您想多次拨打srand(),请不要.其背后的原因是随机生成器初始化例程,该例程基于种子设置变量具有较差的随机特性,比随机生成器本身具有较差的性能,因此不应替代它.

if you think about calling srand() several times, please, don't. the reason behind this is the random generator initialization routine which sets up the variables based on seed has worse random characteristics, gives worse performance than the random generator itself and should be not used as a substitute.

这篇关于随机数和多次下注的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆