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).
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?
UPDATE Assume I either have a unique seed for each thread, or mutex on a global SEED to prevent race conditions.
SEED
. Before worrying about the intricacies of random number generation, it might be more important to get the basics of multi-threading right. Your idea may well be workable, but it's probably not your biggest concern. – Phosphocreatine