/* ---------------------------------------------------------------- */ /* PROGRAM display.c */ /* This program creates two groups of threads. Each thread in */ /* the first group just displays the value of a global counter. */ /* The second group has only one thread that has an infinite loop */ /* that increases the global counter. Thus, this thread never */ /* exits. The main program waits all threads in the first group */ /* and then exits. Consequently, the one thread in the second */ /* group exits as well. */ /* Use the following line to execute this program: */ /* display m n */ /* where m and n are two positive integer. M gives the number of */ /* threads (in the first group); but, m <= 10 must hold. N is the */ /* number of iterations. */ /* ---------------------------------------------------------------- */ #include <stdio.h> #include <stdlib.h> #include <thread.h> #define MAX_THREADS 10 int MaxIteration; int Counter = 0; void *Display(void *ID) { int *intPTR = (int *) ID; int MyID = *intPTR; int i; for (i = 1; i <= MaxIteration/2; i++) printf("Thread %d reporting --> %d\n", MyID, Counter); printf("Thread %d is done....\n", MyID); thr_exit(0); } void *Counting(void *ID) { int i; while (1) { /* this is an infinite loop */ Counter++; if (Counter % 10 == 0) printf("\t\tFrom Counting(): counter = %d\n", Counter); } } void main(int argc, char *argv[]) { thread_t ID[MAX_THREADS]; size_t Status; int NoThreads, i, No[MAX_THREADS]; if (argc != 3) { printf("Use %s #-of-threads #-of-iterations\n", argv[0]); exit(1); } NoThreads = abs(atoi(argv[1])); MaxIteration = abs(atoi(argv[2])); if (NoThreads > MAX_THREADS) { printf("*** ERROR: too many threads ***\n"); exit(0); } thr_create(NULL, 0, Counting, (void *) NULL, 0, NULL); for (i = 0; i < NoThreads; i++) { printf("Parent: about to create thread %d\n", i); No[i] = i; thr_create(NULL, 0, Display, (void *) (&(No[i])), 0, &(ID[i])); } for (i = 0; i < NoThreads; i++) thr_join(ID[i], 0, (void *) &Status); }