From: Jeff Denham <jdenham@brighttiger.com>
Subject: Re: Need help with threads
Date: 1998/04/03 [thread overview]
Message-ID: <3525294E.1BADA019@brighttiger.com> (raw)
In-Reply-To: roy-0204981532510001@qwerky.med.nyu.edu
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. I don't
> understand this; I though the lock/unlock pair around it would solve that
> problem. I know that random() stores internal state, but presumably
> that's in static memory, and thus shared between threads.
>
> What am I doing wrong?
>
> This is on Digital Unix 4.0B, on an alpha.
>
> #include <pthread.h>
> #include <sys/time.h>
>
> pthread_mutex_t random_mutex;
>
> void *go (void *arg)
> {
> int n;
> long d1, d2;
> struct timespec t;
>
> for (n = 1; n <= 10; n++)
> {
> pthread_mutex_lock (&random_mutex);
> d1 = random() % 1000000;
> d2 = random() % 1000000;
> pthread_mutex_unlock (&random_mutex);
>
> t.tv_sec = 0;
> t.tv_nsec = d1 * 1000;
> printf ("thread %d, %d, %ld, %ld\n", (int) arg, n, d1, d2);
> pthread_delay_np (&t);
> }
> }
>
> main ()
> {
> int i1, i2;
> pthread_t t1, t2;
> void *e1, *e2;
> struct timeval tv;
>
> gettimeofday (&tv, NULL);
> srandom ((int) tv.tv_sec);
>
> pthread_mutex_init (&random_mutex, NULL);
>
> i1 = pthread_create (&t1, NULL, go, (void *) 1);
> i2 = pthread_create (&t2, NULL, go, (void *) 2);
>
> pthread_join (t1, &e1);
> pthread_join (t2, &e2);
> }
>
> --
> Roy Smith <roy@popmail.med.nyu.edu>
> New York University School of Medicine
Well, for starters, try using rand_r(). Then report back ;^)
__________________________________________________
Jeff Denham (jdenham@brighttiger.com)
Bright Tiger Technologies
SmartCluster� Software for Distributed Web Servers
http://www.brighttiger.com
125 Nagog Park
Acton, MA 01720
Phone: (978) 263-5455 x177
Fax: (978) 263-5547
next prev parent reply other threads:[~1998-04-03 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 [this message]
1998-04-04 5:00 ` Gerald A. Feldman
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