From mboxrd@z Thu Jan 1 00:00:00 1970 X-Google-Language: ENGLISH,ASCII-7-bit X-Google-Thread: fee84,626226e0e2875e9c,start X-Google-Attributes: gidfee84,public From: roy@popmail.med.nyu.edu (Roy Smith) Subject: Need help with threads Date: 1998/04/02 Message-ID: #1/1 X-Deja-AN: 340293519 X-License-Fee: $10 per copy for commercial use X-Complaints-To: usenet@news.nyu.edu X-Trace: news.nyu.edu 891549171 25571 (None) 128.122.205.14 Organization: NYU School of Medicine, Educational Computing X-Redistribution-Policy: Commercial redistribution prohibited without license fee paid in advance Newsgroups: comp.unix.osf.osf1 X-Copyright: Copyright 1997 Roy Smith 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