This is the mail archive of the mailing list for the glibc project.

Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: random number generators - rand(), random(), etc

On Fri, Nov 7, 2014 at 1:51 PM, jb <> wrote:
> rand(3)
>   The function rand() is not reentrant or thread-safe, since it uses hidâ
>   den 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 elaboâ
>   rate.  In order to get reproducible behavior in a threaded application,
>   this  state must be made explicit; this can be done using the reentrant
>   function rand_r().
> rand_r(3)
>      (...)
>      The   function   rand_r()   is   from   POSIX.1-2001.
>      POSIX.1-2008 marks rand_r() as obsolete.
>     (...) rand()  implementations (...)
>     Do  not use this function in applications intended to be
>     portable when good randomness is needed.  (Use random(3) instead.)
> But,
> - pthread(7) - the function random() is listed as threadsafe.
> - random(3)
>   Multithreading (see pthreads(7))
>        The random(), srandom(),  initstate(),  and  setstate()  functions
>        are thread-safe.
> Well, what function(s) are available in Linux glibc that would be safe to
> use where requirement for threadsafety and/or reentrancy were important ?

The man pages are quite clear. random() is specified to be
thread-safe. rand() is not specified to be thread-safe. rand() happens
to be thread-safe with the current implementation , but as stated in
'man 3p rand' (the POSIX man page), this isn't guaranteed. So you
cannot portably assume rand() is thread-safe.

None of rand(3) and random(3) are reentrant.

rand_r(3) and random_r(3) are specified to be both thread-safe and
reentrant. Therefore: use these.

Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]