Search code examples
c++cmultithreadingrandom

Using stdlib's rand() from multiple threads


I have several threads which all run the same function. In each of these they generate a different random number several times. We tried to do this by putting srand(time(0)) at the start of the function, but it seems that they all get the same number.

Do we need to call srand(time(0)) only once per program, i.e at the start of main (for example), at the start of each function that is called several times, or something else?


Solution

  • srand() seeds the random number generator. You should only have to call srand(time(NULL)) once during startup.

    That said, the documentation states:

    The function rand() is not reentrant or thread-safe, since it uses hidden state that is modified on each call. This might just be the seed value to be used by the next call, or it might be something more elaborate. In order to get reproducible behaviour in a threaded application, this state must be made explicit. The function rand_r() is supplied with a pointer to an unsigned int, to be used as state. This is a very small amount of state, so this function will be a weak pseudo-random generator. Try drand48_r(3) instead.

    The emphasized part of the above is probably the reason why all your threads get the same number.