rand() is racy in multi-threaded programs?

Conrad Meyer cem at freebsd.org
Wed Dec 2 23:20:41 UTC 2020


Hi Andriy,

Rand(3) is explicitly unsafe to use from concurrent threads without some
external serialization, even after initialization. I’d suggest using a
different API.

Best,
Conrad

On Wed, Dec 2, 2020 at 13:53 Andriy Gapon <avg at freebsd.org> wrote:

>
> Specifically, concurrent "first" calls to rand().
> There can be a moment when rand3_state is allocated but not completely set
> up
> with initstate_r().
> Is this a known / documented issue?
> Should we try to do better?
>
> P.S.
> I am seeing this issue from time to time when running ztest program (from
> ZFS).
> I guess that it uses rand() just because that's what OpenZFS did / does on
> illumos and Linux.
>
> P.P.S.
> Just realized that the problem can be relatively recent.
> https://svnweb.freebsd.org/base?view=revision&revision=357382
>
> --
> Andriy Gapon
>


More information about the freebsd-current mailing list