Welcome to the CC ++ programming Community Forum and interact with 2 million technical staff. Today, when you debug a program, we find that the rand () random function in a thread returns the same data every time it runs, after checking the program, the program also calls srand (GetTicketCount () to initialize the random number generator. Why is the result still the same?
Welcome to the C/C ++ programming community forum, and interact with 2 million technical staff> enter the rand () in a thread found during program debugging today () every time a random function runs, it returns the same data, checks the program, and CALLS srand (GetTicketCount () in the program to initialize the random number generator. Why is the result the same?
Welcome to the C/C ++ programming Community Forum and interact with 2 million technical staff> enter
Today, when debugging the program, we found that the rand () random function in a thread returns the same data every time it runs, checked the program, and also called srand (GetTicketCount () in the program ()) to initialize the random number generator. Why is the result the same ???
Later, I found that this problem is related to multithreading. After tracking the srand and rand functions, I found that srand and rand use functions such as TlsGetValue to store Random Seed internally. That is to say, this random number seed needs to initialize srand for each thread, and the previous code is initialized once in the main thread. Of course, the result is the same every time.
Void _ cdecl srand (
Unsigned int seed
)
{
# Ifdef _ MT
_ Getptd ()-> _ holdrand = (unsigned long) seed;
# Else/* _ MT */
Holdrand = (long) seed;
# Endif/* _ MT */
}
_ Ptiddata _ cdecl _ getptd (
Void
)
{_ Ptiddata ptd;
DWord TL_LastError;
TL_LastError = GetLastError ();
If (ptd = TlsGetValue (_ tlsindex) = NULL ){
/*
[1] [2]