rand is not ISO C compliant in Cygwin
Corinna Vinschen
corinna-cygwin@cygwin.com
Tue Nov 14 10:11:01 GMT 2023
Hi Bruno,
On Nov 13 22:33, Bruno Haible via Cygwin wrote:
> Corinna Vinschen wrote:
> > https://pubs.opengroup.org/onlinepubs/9699919799/functions/rand.html
> > [...]
> > With regard to rand(), there are two different behaviors that may be
> > wanted in a multi-threaded program:
> >
> > 1. A single per-process sequence of pseudo-random numbers that is
> > shared by all threads that call rand()
> >
> > 2. A different sequence of pseudo-random numbers for each thread that
> > calls rand()
> > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
>
> This paragraph continues after the two items:
> "This is provided by the modified thread-safe function based on whether
> the seed value is global to the entire process or local to each thread."
>
> My understanding of this paragraph is:
> - If an application wants 1., they can use rand_r with SEED pointing
> to a global variable.
> - If an application wants 2., they can use rand_r with SEED pointing
> to a per-thread variable.
The problem I have with bringing rand_r() into the picture at this point
is two-fold:
- The paragraph explicitely states "With regard to rand() ..."
- rand_r() is obsolescent and may be removed in a future version.
The rational section is entirely dedicated to the base functions
rand()/srand() and doesn't mention rand_r() even once. I don't see
that the vague expression "the modified thread-safe function" is really
meant to be rand_r(), or rather rand() after an implementation decides
to make rand() thread-safe.
> > I read this as the newlib technique being one way of correctly
> > implementing rand/srand, no?
>
> I don't think so. The critical sentence is the one with
> "subsequent calls to rand".
I see what you mean. However, what sense is there in providing a global
state, while at the same time rand() doesn't need to be thread-safe. In
the end, if you call srand() once and then run rand() in concurrent
threads, the implementation has no control over the sequences generated
per-thread, unless your application threads will sync the calls explicitely.
We have a potential patch to align rand/srand to your interpretation,
at least for Cygwin if nobody else in the newlib community chimes in.
It's just that, personally, I'm not yet convinced that this is the only
possible interpretation.
Sigh... yet another case of unnecessary vagueness in the standards...
Thanks,
Corinna
More information about the Cygwin
mailing list