From: "Gerald A. Feldman" <"gafNoSPAM"@mediaone.net (Remove NoSpam)>
To: Roy Smith <roy@popmail.med.nyu.edu>
Subject: Re: Need help with threads
Date: 1998/04/04 [thread overview]
Message-ID: <6g6dgt$fdt$1@ndnws01.ne.highway1.com> (raw)
In-Reply-To: 3525294E.1BADA019@brighttiger.com
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.
<snip>
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 <gaf@mediaone.net>
Boston Computer Solutions and Consulting
http://gaf.ne.mediaone.net/
prev parent reply other threads:[~1998-04-04 5:00 UTC|newest]
Thread overview: 3+ messages / expand[flat|nested] mbox.gz Atom feed top
1998-04-02 5:00 Need help with threads Roy Smith
1998-04-03 5:00 ` Jeff Denham
1998-04-04 5:00 ` Gerald A. Feldman [this message]
read-only archive
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox