Is there an alternative to using time to seed a random number generation?

前端 未结 10 642
既然无缘
既然无缘 2020-11-27 06:30

I\'m trying to run several instances of a piece of code (2000 instances or so) concurrently in a computing cluster. The way it works is that I submit the jobs and the clust

10条回答
  •  失恋的感觉
    2020-11-27 07:02

    Windows

    Provides CryptGenRandom() and RtlGenRandom(). They will give you an array of random bytes, which you can use as seeds.

    You can find the docs on the msdn pages.

    Linux / Unixes

    You can use Openssl's RAND_bytes() to get a random number of bytes on linux. It will use /dev/random by default.

    Putting it together:

    #ifdef _WIN32
      #include 
    #else
      #include  
    #endif
    
    uint32_t get_seed(void)
    {
      uint32_t seed = 0;
    
    #ifdef _WIN32
      RtlGenRandom(&seed, sizeof(uint32_t) );
    #else
      RAND_bytes(&seed, sizeof(uint32_t) ); 
    #endif
    
      return seed;
    }
    

    Note that openssl provides a Cryptographically secure PRNG by default, so you could use it directly. More info here.

提交回复
热议问题