Path: csiph.com!eternal-september.org!feeder.eternal-september.org!reader01.eternal-september.org!.POSTED!not-for-mail From: Keith Thompson Newsgroups: comp.lang.c Subject: Re: Multi-channel rand() Date: Thu, 27 Dec 2018 12:47:44 -0800 Organization: None to speak of Lines: 43 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Injection-Info: reader01.eternal-september.org; posting-host="32ed57ea5d614545634ff390fd99b31b"; logging-data="6646"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/JmXAkg0G0wn5mZg8CPxYJ" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/23.1 (gnu/linux) Cancel-Lock: sha1:S6SlS0junnXDc4aduzsAPNLTcj4= sha1:mQOwz2PfusRGBbyijas62k6kGiY= Xref: csiph.com comp.lang.c:139141 James Kuyper writes: > On Thursday, December 27, 2018 at 2:29:01 PM UTC-5, Keith Thompson wrote: >> James Kuyper writes: >> > On Thursday, December 27, 2018 at 9:46:42 AM UTC-5, Bart wrote: >> [...] >> >> OK (it sounds like random() doesn't support independent sequences). >> > >> > It does, through the initstate() and setstate() functions. >> >> Yes, but you'd have to save and restore the entire state on each >> call, or at least each time you want to switch to a different >> sequence. > > Was the example code I gave to Rick coded incorrectly? This is a feature > I've never personally used, so I may have made a mistake, but that code > did not save or restore any state, because the interface doesn't seem to > require doing so. I was wrong. The initstate() function returns a pointer to the state (as a char*), and setstate() returns a pointer to the previous state. I'm going to assume your example code was probably correct, but I didn't save a copy. So if you want multiple streams using random(), you could do something like: setstate(pointer_to_state_for_this_thread); long int r = random(); But if you want a distinct stream for each thread, you'd have to use some kind of synchronization to ensure that there's no context switch between the setstate() and random() calls. Since I misunderstood the state management the last time I read the man page, it's entirely possible that I've misunderstood it again in some new and embarrassing way. -- Keith Thompson (The_Other_Keith) kst@mib.org Will write code for food. "We must do something. This is something. Therefore, we must do this." -- Antony Jay and Jonathan Lynn, "Yes Minister"