When employing multiple threads that invoke a common function tasked with generating distinct random numbers, it is crucial to consider the approach for initializing the random number generator. The function srand(time(0)) is responsible for initializing the generator. However, its placement within the code can impact the consistency of the results.
The question arises as to whether srand(time(0)) should be invoked once for the entire program, at the beginning of each function execution, or if there is an alternative strategy.
The answer lies in the thread safety concerns associated with rand(). The documentation explicitly states that rand() is not thread-safe, meaning that it modifies hidden state with each invocation. To ensure consistent behavior across threads, the state must be handled explicitly.
The alternative function rand_r() accepts a pointer to an unsigned integer as state, providing a minimal amount of state information. This function will result in a weaker pseudo-random generator. As an enhanced option, drand48_r(3) is recommended.
Therefore, to maintain predictable random number generation across multiple threads, it is necessary to utilize thread-safe functions like rand_r() or drand48_r(3) instead of rand().
The above is the detailed content of How Can I Ensure Thread-Safe Random Number Generation in C ?. For more information, please follow other related articles on the PHP Chinese website!