This is the mail archive of the
libc-alpha@sourceware.org
mailing list for the glibc project.
Re: random number generators - rand(), random(), etc
- From: jb <jb dot 1234abcd at gmail dot com>
- To: libc-alpha at sourceware dot org
- Date: Fri, 7 Nov 2014 21:51:01 +0000 (UTC)
- Subject: Re: random number generators - rand(), random(), etc
- Authentication-results: sourceware.org; auth=none
- References: <loom dot 20141107T185212-863 at post dot gmane dot org> <CAH_=xoaB7zNpcTXu72nq1gjRYhJDsVjheMh5gOsYCwZgPHRAOQ at mail dot gmail dot com> <loom dot 20141107T210031-509 at post dot gmane dot org> <CAH_=xoZ4GMPEXpYALhS4JRxWx2y4VdqGSKLfSbPBKYNJ9H=oCQ at mail dot gmail dot com>
Eric Rannaud <e <at> nanocritical.com> writes:
>
> On Fri, Nov 7, 2014 at 12:07 PM, jb <jb.1234abcd <at> gmail.com> wrote:
> > But, if they share the *single instance* of the generator, does it not make
> > both of them non-reentrant and non-threadsafe since they share a state (it
> > might be e.g. a seed value) that is modified on each call by one of them ?
>
> They are thread-safe, actually. But not reentrant. As per the man
> pages. See rand_r() and random_r() for reentrant versions.
>
>
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)
CONFORMING TO
(...)
The function rand_r() is from POSIX.1-2001.
POSIX.1-2008 marks rand_r() as obsolete.
NOTES
(...) 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 ?
jb