Multithreaded Random Number Generation with stdlib's rand()
When generating random numbers from multiple threads that execute the same function, it's crucial to understand how the rand() function operates.
Significance of srand(time(0))
srand(time(0)) initializes the seed for the random number generator. It's generally recommended to call this function only once per program, ideally at the beginning of the main() function. This ensures a unique seed for the entire program's duration.
Thread Safety Considerations
However, it's important to note that rand() is not thread-safe, meaning it's not guaranteed to produce unique numbers when used by multiple threads concurrently. As the documentation states, it uses hidden state that gets modified upon each call.
Alternatives for Multithreaded Applications
For thread-safe random number generation, it's advisable to use the rand_r() function instead. This function takes an explicit state parameter, which allows multiple threads to seed the generator independently.
Alternatively, the drand48_r(3) function offers a high-quality pseudorandom generator suitable for multithreaded environments. It uses a larger internal state than rand_r(), resulting in better randomness quality.
The above is the detailed content of How Can I Generate Thread-Safe Random Numbers in C ?. For more information, please follow other related articles on the PHP Chinese website!