views:

124

answers:

2

Hey,

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.

+3  A: 

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.

Greg Hewgill
The Windows equivalent is to use the CSP, not generate a GUID.
Steven Sudit
True, but if you don't have a high-security need, then generating a UUID is simpler than using the CSP. Note that Windows no longer generates sequential UUIDs by default.
Greg Hewgill
I agree that a UUID is simpler and that it's generated using a PRNG rather than a simple sequence. However, it remains the case that the CSP's CryptGenRandom function is the equivalent of urandom and is more secure than UUID's.
Steven Sudit
How can I check from within the program (C++) in which platform am I?
R S
Could use data from http://www.random.org/ to seed it
Merlyn Morgan-Graham
@R S: Usually I've seen this done in pre-compiler directives to look for compiler version, or with custom #defines. If you're using something like autotools to do your build, you can use its existing facilities to see if you have various functions (configure)
Merlyn Morgan-Graham
@RS: if you're using Visual C++ on Windows, and perhaps other Windows compilers, you can #ifdef _WIN32 / #else / #endif around your Windows code.
Tony
A: 

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
}
Martin York