From mboxrd@z Thu Jan 1 00:00:00 1970 X-Google-Language: ENGLISH,ASCII X-Google-Thread: fee84,626226e0e2875e9c X-Google-Attributes: gidfee84,public From: Jeff Denham Subject: Re: Need help with threads Date: 1998/04/03 Message-ID: <3525294E.1BADA019@brighttiger.com>#1/1 X-Deja-AN: 340582393 Content-Transfer-Encoding: 8bit References: Content-Type: text/plain; charset=iso-8859-1 Organization: Bright Tiger Technologies 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. 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 > #include > > 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 > 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