From mboxrd@z Thu Jan 1 00:00:00 1970 X-Google-Language: ENGLISH,ASCII-7-bit X-Google-Thread: fee84,626226e0e2875e9c X-Google-Attributes: gidfee84,public From: "Gerald A. Feldman" <"gafNoSPAM"@mediaone.net (Remove NoSpam)> Subject: Re: Need help with threads Date: 1998/04/04 Message-ID: <6g6dgt$fdt$1@ndnws01.ne.highway1.com>#1/1 X-Deja-AN: 340925982 Content-Transfer-Encoding: 7bit References: <3525294E.1BADA019@brighttiger.com> To: Roy Smith Content-Type: text/plain; charset=us-ascii Organization: Boston Computer Solutions and Consulting Mime-Version: 1.0 Newsgroups: comp.unix.osf.osf1 Roy Smith wrote: > > I'm trying to teach myself threads. I wrote a little test program (shown > below) which creates 2 threads. Each thread just counts to 10, delaying a > short time after each iteration. > > The problem is, when I run it, I get this: > > thread 1, 1, 917053, 302914 > thread 2, 1, 917053, 302914 > thread 1, 2, 100827, 210302 > thread 2, 2, 100827, 210302 > thread 1, 3, 253631, 600785 > thread 2, 3, 253631, 600785 > [etc] > > It's obvious that what's going on is that something is thread-unsafe about > random(), and it's returning the same sequence to each thread. This is expected behavior. The random() function should be thread safe in DU 4.0C. You made an assumption:"random() stores internal state, but presumably that's in static memory, and thus shared between threads". This is an incorrect assumption. Thread safeness means that multiple threads will not be side effected. All functions in libc (such as random(), ctime(), getutent(), malloc() ... are given a per-thread context. You do not need to wrap them with a mutex. You results would be identical if your program forked itself and ran as separate processes. Your results would be the same if you ran the rand_r() function. -- Jerry Feldman Boston Computer Solutions and Consulting http://gaf.ne.mediaone.net/