Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Properly seeding rand_r(int *val) method

Tags:

c

pointers

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!

like image 940
user1742385 Avatar asked Oct 13 '12 02:10

user1742385


1 Answers

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
    }
}
like image 70
Kerrek SB Avatar answered Sep 21 '22 11:09

Kerrek SB