So I have multiple threads which will be using the rand_r function. The signature of this function is :
int rand_r(int *val);
I was trying to use the time to seed this function but I'm having all kinds of trouble. Could anyone explain to me how I would call rand_r using time, or some other simple way to seed rand_r dynamically.
Thanks!
For the reentrant version rand_r
, the seed is just the initial value of the state .You need one seed per thread. Either create an array of seeds, or make the seed variable thread-local:
_Thread_local unsigned int seed = time(NULL);
int do_stuff()
{
for ( ; ; )
{
int n = rand_r(&seed);
// use n
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With