Consider the program
collatz.c
given below:
1 #include <unistd.h>
2 #include <stdio.h>
3 #include <pthread.h>
4
5 unsigned int volatile next = 2; // Ignore the "volatile" keyword here!
6 int maxes[4] = {0,0,0,0}, N[4] = {0,0,0,0};
7
8 int collatz(unsigned int n, int k) { return n == 1 ? k : collatz((n%2 ? 3*n+1 : n/2),k+1); }
9
10 void* checkerThread(void * p)
11 {
12 int id = pthread_self();
13 while(1)
14 {
15 int mp = collatz(next,1);
16 if (mp > maxes[id]) { maxes[id] = mp; N[id] = next; }
17 ++next;
18 }
19 }
20
21 int main()
22 {
23 pthread_t ltA, ltB;
24 pthread_create(<A,NULL,checkerThread,NULL);
25 pthread_create(<B,NULL,checkerThread,NULL);
26 do {
27 sleep(1);
28 printf("next = %i: A -> %i,%i: B -> %i,%i\n",next,maxes[ltA],N[ltA],maxes[ltB],N[ltB]);
29 } while(next < 100000000);
30 return 0;
31 }
-
How many threads total are there for this program?
-
What are the "shared resources" for this program?
-
What is the "critical section" for this program? (Give the
line numbers!)
-
Show how to rewrite
checkerThread to reduce the
time spent in the "critical section"? Be sure to point out
which lines in the new code actually constitute the critical section!