rand() is racy in multi-threaded programs?
Conrad Meyer
cem at freebsd.org
Thu Dec 3 07:44:37 UTC 2020
Hi Andriy,
On Wed, Dec 2, 2020 at 11:34 PM Andriy Gapon <avg at freebsd.org> wrote:
>
> On 03/12/2020 01:20, Conrad Meyer wrote:
> > Rand(3) is explicitly unsafe to use from concurrent threads without some
> > external serialization, even after initialization. I’d suggest using a different
> > API.
>
> thank you!
> Just want to check, unsafe in terms of bogus results (with respect to
> randomness) or unsafe as in may crash?
Well, unsafe in that it's a data race, which is formally undefined
behavior in C (if I understand correctly). So anything could happen,
including a crash. In practice, you would probably see something more
like the former (bogus results, e.g., multiple calls returning the
same number because the state wasn't updated atomically, or something
like that) rather than a crash.
Best,
Conrad
More information about the freebsd-current
mailing list