Home >Backend Development >C++ >How Can I Generate Unique Random Numbers in Multiple Threads Using C's `rand()` Function?
In multithreaded programming scenarios, it is often necessary to generate random numbers in separate threads. However, when using the standard library's rand() function, you may encounter issues if not handled correctly.
Multiple threads executing the same function produce the same random number repeatedly. This is because each thread typically has its own copy of global data, including rand()'s internal state, which is shared by all threads.
To avoid generating the same random numbers, it is necessary to explicitly manage the internal state of rand(). The documentation recommends the following:
For example, to use rand_r() in a multithreaded environment, you could:
#include <stdlib.h> void* thread_function(void* arg) { unsigned int state = 0; // Thread-specific state while (1) { int random_number = rand_r(&state); // Do something with random_number } return NULL; }
It should be noted that using rand() or rand_r() without proper thread synchronization can lead to unpredictable behavior and incorrect results. Always ensure proper synchronization mechanisms are in place to handle multithreaded access to shared resources, including random number generators.
The above is the detailed content of How Can I Generate Unique Random Numbers in Multiple Threads Using C's `rand()` Function?. For more information, please follow other related articles on the PHP Chinese website!