Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!1.eu.feeder.erje.net!newsfeed.fsmpi.rwth-aachen.de!newsfeed.straub-nv.de!eternal-september.org!feeder.eternal-september.org!mx02.eternal-september.org!.POSTED!not-for-mail From: Keith Thompson Newsgroups: comp.lang.c Subject: Re: thread-safe random numbers... Date: Thu, 28 May 2015 12:38:03 -0700 Organization: None to speak of Lines: 35 Message-ID: <87iobclch0.fsf@kst-u.example.com> References: Mime-Version: 1.0 Content-Type: text/plain Injection-Info: mx02.eternal-september.org; posting-host="9be37d943435275679235b07c7947eef"; logging-data="23074"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18La9uh1/8LTqClRdH6hFoT" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/24.3 (gnu/linux) Cancel-Lock: sha1:0U4D4KQXknmGogWPRclIiUr5gGY= sha1:hy7q4G3qrmbt0+zVEvm+0ueezF8= Xref: csiph.com comp.lang.c:62744 James Kuyper writes: [...] > rand() has never been the recommended way of doing serious random number > generation - the standard imposes no meaningful restrictions on the > quality of the algorithm it uses. Older versions of the standard > actually gave a specific and very unsophisticated algorithm as an > example, and many implementations actually implemented that algorithm. > Creating your own random number generator, or borrowing someone else's, > is the recommended approach for serious random number generation. While > doing so, you can make it thread-safe. The current standard still has that sample implementation (as a non-normative example). Some implementations have a rand() function that's even worse; unlike the sample version in the standard, some versions return values in which the low-order bit alternates on each call, the low-order 2 bits have a cycle of 4, and so on. (I think it's one of the BSDs.) > If you're willing to restrict the portability of your code to POSIX > platforms, and a simple 48-bit linear congruential algorithm would be > sufficient for your needs, you can use erand48(), nrand48() or > jrand48(), depending upon whether you want the range of the random > numbers to be [0.0,1.0), [0,2^31) or (-2^31,2^31). The corresponding > drand48(), lrand48() and jrand48() functions are NOT guaranteed to be > thread-safe. If the mediocre implementation given in the standard is good enough, it's easy to adapt to be thread-safe. -- Keith Thompson (The_Other_Keith) kst-u@mib.org Working, but not speaking, for JetHead Development, Inc. "We must do something. This is something. Therefore, we must do this." -- Antony Jay and Jonathan Lynn, "Yes Minister"