Seed random from milliseconds in Windows and Linux

2019-03-31 20:13发布

I need to seed the random number generator in boost (which is loaded from an int) for a few processes, for a program that has to compile and work both in Windows and in Linux.

I used std:time(0), which worked, but since the processes are jobs which are run simultaneously, some of them would run at the same second, producing the same results.

So I need to seed it from milliseconds, or any other cross-platform random generator for that matter. I tried clock() but couldn't quite make it convert from time_t to int.

Thanks.

2条回答
劳资没心,怎么记你
2楼-- · 2019-03-31 20:28

You are probably best off using a platform-specific random number source. On Linux, use /dev/urandom and read a few bytes. On Windows, a simple way to acquire a few bytes of entropy is UuidCreate.

查看更多
Rolldiameter
3楼-- · 2019-03-31 20:30

If you are starting all the jobs from a single script.

Then you could pass an incremented number as an argument on the command line. Each Job then adds this value to the result of time() to generate its seed.

Note: I don't see any requirement in the OP about security.
The original code is using time(NULL) and this will has a guessable seed.

int main(int argc,char* argv[])
{
    srand(time(NULL) + boost::lexical_cast<int>(argv[1]));

    // STUFF
}
查看更多
登录 后发表回答