PROBLEM:
In my program, rand()
is called twice, and on last call, the return value is always same.
The first call with srand()
, returns different value, everytime I run the process;
I read several answers here :
rand() returns the same value, even after a srand
rand() returns same values when called within a single function
srand function is returning same values
All of them say that - call srand()
only once in a process, that is the solution - , but in my case that is not the solution.
I append my code and debug result.
CODE:
int rand_history[100000], rand_cnt = 0;
int randNum(int max, int min = 0)
{
static bool s_seedCalled = false;
if (!s_seedCalled) {
srand(time(0));
s_seedCalled = true;
}
int rnd = rand();
rand_history[rand_cnt++] = rnd;
int range = max - min;
if (range <= 0) return rnd;
return rnd % range + min;
}
UI thread:
randNum(10); // 1st call
thread 1:
randNum(40 * 60 + 1) // 2nd call
DEBUG RESULT:
rand_history = { 14279, 41 } // 1st run
= { 14589, 41 } // 2nd run
= { 14831, 41 } // 3rd run
= { 14988, 41 } // 4th run
....
Is there anybody explain this situation and help me to deal with this problem?
Any suggestion or reply would be appreciated. Thansk. :)
Aucun commentaire:
Enregistrer un commentaire