samedi 16 octobre 2021

rand() returns same value at 2nd call, even returned different value at 1st call [duplicate]

BEGGING:
PLEASE DO NOT close my question, I couldn't find any solution from duplicating questions and answer.
I asked this question 3 times and looking forward your suggestions.

Please.

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
Using stdlib's rand() from multiple threads : my first question was duplicated with this, but I couldn't find any solution here.

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
             = { 21073, 41 }   // 4th run
             = { 21342, 41 }   // 5th run
             = { 21633, 41 }   // 6th run
              ....

As you can see, there is no synchronization about s_seedCalled and rand_cnt.
It's not necessary, because UI thread's call is only once on startup and thread1's call is exclusive with UI thread.
It's just to say that randNum() is called in different thread, and I wonder that calls in different threads might affect the DEBUG RESULT.

QUESTION:
What Is the reason the second values are all same, even the first values are different?
Is there anybody explain this situation and help me to deal with this problem?

Any suggestion or reply would be appreciated. Thanks. :)

p.s. I asked this question hours ago, and it's closed with duplication.
I cound't find any solution about this problem from the duplicating Questions.




Aucun commentaire:

Enregistrer un commentaire