/* tab:4 * * psample.c - Sample PTHREADS PROGRAM * */ static char _version_string_[] = "\nVersion:1:psample.c\0\n"; #include #include #include #define _REENTRANT #include #define MAXTHREADS 32 pthread_t tid[MAXTHREADS]; int ready[MAXTHREADS]; volatile int NTHREADS = 0; volatile int go = 0; pthread_mutex_t report_mp = PTHREAD_MUTEX_INITIALIZER; int node = 0; int reports[MAXTHREADS]; /* Update within critical section for shared data structure */ void report_in (int p) { pthread_mutex_lock(&report_mp); reports[node] = p; node++; pthread_mutex_unlock(&report_mp); } void *start_fun(void *arg) { volatile int barf = 0; int i, seed; int vp = (int)arg; int self = pthread_self(); while (go == 0) { } /* Wait to main have everyone created */ /* spin a random time */ seed = vp; srand(seed); for (i = (rand() & 0xffffff); i>0; i--) { barf++; } printf("thread %d looped %d times\n", vp, barf); /* Report in through critical section */ report_in(vp); } int main(int argc, char *argv[]) { int i, p, create_status; pthread_attr_t attr; if (argc <= 1) { fprintf(stdout, "usage %s NTHREADS\n", argv[0]); exit(1); } NTHREADS = atoi(argv[1]); if ((NTHREADS < 2) || (NTHREADS > MAXTHREADS)) { fprintf(stdout, "usage %s NTHREADS - where NTHREADS > 1.\n", argv[0]); exit(1); } printf("%d processors\n", NTHREADS); pthread_attr_init(&attr); pthread_attr_setscope(&attr, PTHREAD_SCOPE_PROCESS); /* Create a collection of worker threads - all at start_fun */ for (p = 0; p< NTHREADS; p++) { ready[p] = 0; create_status = pthread_create(&tid[p], &attr, start_fun, (void *) p); if (create_status != 0) printf("Error creating threads %d\n",p); } go = 1; /* Cheap and dirty barrier */ /* Wait for them all to finish */ for (p = 0; p< NTHREADS; p++) { pthread_join(tid[p],NULL); } /* Print out there reporting order */ for (i = 0; i< NTHREADS; i++) { printf ("%d->%d.\n", i, reports[i]); } }