random numbers and multiple srand calls

前端 未结 3 1914
长情又很酷
长情又很酷 2021-01-18 09:24

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 c

3条回答
  •  忘掉有多难
    2021-01-18 10:14

    srand() will reset the stream of numbers rand() will generate for you.

    From the manual for srand:

       The srand() function sets its argument as the seed for a  new  sequence
       of  pseudo-random  integers  to be returned by rand().  These sequences
       are repeatable by calling srand() with the same seed value.
    

    If you need "better" random numbers then rand() provides you should look into other sources of randomness.

    Also srand() is not used for rand_r(), the argument you provide (to rand_r()) is used instead.

    And if you want to use rand_r() from multiple threads all threads should have a local seed, you shouldn't use a single global variable for that.

    Alternatives to rand() can be Mersenne Twister

    But if you need "real" randomness you have to look hardware support.

    And to answer:

    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?

    No, doesn't work that way, you should have a thread-local SEED variable initialized to something unique for every thread. You could use time() for the first seed, and then use that random sequence to generate seeds for the other threads, or you read 4-8 bytes from /dev/random or /dev/urandom if you'r using *nix.

    Hope that gives some insight as this is midnight rumble, good night <3

提交回复
热议问题