/* ---------------------------------------------------------------- */ /* PROGRAM ex2.c */ /* This program creates two threads, Counting() and Peeking(). */ /* Counting() keeps increasing the value of a shared counter, while */ /* Peeking() keeps taking the value of the shared counter. However,*/ /* Peeking() only reports the value every 100 iterations. If the */ /* iteration number is not a multiple of 100, Peeking() enters a */ /* dummy loop for killing time. Note that Peeking() never modifies */ /* the value of the shared counter. */ /* ---------------------------------------------------------------- */ #include <stdio.h> #include <thread.h> #define MAX_ITERATION 2000 int Counter = 0; void *Counting(void *DontNeedIt) { int i; for (i = 1; i <= MAX_ITERATION; i++) { Counter++; printf("Thread Counting() has updated the counter to %d\n", Counter); } thr_exit(0); } void *Peeking(void *DontNeedIt) { int i; int j, k; for (i = 1; i <= MAX_ITERATION; i++) if (i % 100 == 0) printf(" Thread Peeking() saw the counter as %d\n", Counter); else /* the following is a dummy loop */ for (j = k = 0; j <= MAX_ITERATION/2; j++, k += j) ; thr_exit(0); } void main(void) { thread_t FirstThread, SecondThread; size_t StatusFromA, StatusFromB; thr_create(NULL, 0, Counting, (void *) NULL, 0, &FirstThread); thr_create(NULL, 0, Peeking, (void *) NULL, 0, &SecondThread); thr_join(FirstThread, 0, (void *) &StatusFromA); thr_join(SecondThread, 0, (void *) &StatusFromB); }