Re: rand is not ISO C compliant in Cygwin

Corinna Vinschen via Cygwin <[email protected]>
Newsgroups gmane.os.cygwin,gmane.comp.lib.newlib
Message-ID <[email protected]>
On Nov 13 17:14, Glenn Strauss wrote:
> On Mon, Nov 13, 2023 at 10:33:48PM +0100, Bruno Haible via Cygwin wrote:
> > POSIX does not have these two sentences, but instead has:
> > 
> >   "The rand() function need not be thread-safe."
> 
> I read the above as requiring *reentrancy*, but not *thread-safety*.
> 
> If multiple threads are accessing rand() and rand() accesses global
> state, the global state should not get corrupted; the sequence
> generated by rand() should remain intact.  Since thread-safety is not
> guaranteed, is it theoretically possible that multiple threads enter
> rand() at nearly the same time and both get the *same* random value in
> the sequence.  (Whether or not that is undesirable behavior is
> application-specific.)  A mutex can avoid this theoretical duplication,
> as can using thread-local state (with difference seeds) instead of
> global state.  If the seed value is the same in multiple threads using
> thread-local state, the sequence of random values generated in each
> thread will be repeated in each thread.  This may be surprising behavior
> to some when srand() is called, then multiple threads spawned, and each
> thread subsequently gets the same sequence of values from rand().

That's a good common sense argument for changing rand() to use a global
state.


Corinna


-- 
Problem reports:      https://cygwin.com/problems.html
FAQ:                  https://cygwin.com/faq/
Documentation:        https://cygwin.com/docs.html
Unsubscribe info:     https://cygwin.com/ml/#unsubscribe-simple
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.