Programming Skills random number initialization under multiple threads

Source: Internet
Author: User
Tags random seed
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]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.