Usenet comp.unix.osf.osf1 (1992-2004)
 help / color / mirror / Atom feed
* Need help with threads
@ 1998-04-02  5:00 Roy Smith
  1998-04-03  5:00 ` Jeff Denham
  0 siblings, 1 reply; 3+ messages in thread
From: Roy Smith @ 1998-04-02  5:00 UTC (permalink / raw)



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




^ permalink raw reply	[flat|nested] 3+ messages in thread

end of thread, other threads:[~1998-04-04  5:00 UTC | newest]

Thread overview: 3+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
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 is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox