1. For the threadHello program in Figure 4.6, the procedure go() has the paramet
ID: 3829136 • Letter: 1
Question
1. For the threadHello program in Figure 4.6, the procedure go() has the parameter np and the local variable n Are these variables per-thread or shared state? Where does the compiler store these variables states?
2. For the threadHello program, what is the minimum and maximum number of times that the main thread enters the WAITING state?
142 Chapter 4. urrency and Threads #include . #include thread.h thread Hello static void go (int n); Hello from thread Hello from thread 1 Thread 0 ret Hello from 100 thread 3 #define NTHREADS 10 static thread t threads INTHREADS]; Hello from thread 4 Thread 1 returned 101 int main (int argc, char argv) nt i Hello from thread 5 Hello from thread 2 long exit value Hello from thread 6 Hello from thread 8 for (i 0; i NTHREADS: i ++)t Hello from 7 thread create (& (threads [i]) &go;, i); Hello from thread 9 Thread 2 returned 102 for (i 0; i NTHREADS; i++) Thread 3 returned 103 exit Value thread join (threads i 1) Thread 4 returned 104 Thread 5 returned 105 printf ("Thread %d returned with dIn Thread 6 returned 106 i exit value) Thread 7 returned 107 Thread 8 returned 108 printf Main thread done In Thread 9 returned 109 return 0; void go (int n) printf Hello from thread %d n n); thread exit (100 n); Not reached Figure 4.6: Example multi-threaded program using the simple threads API that prints "Hello" ten times. The right side shows the output of one possible run of this program. 4.3.1 A Multi-Threaded Hello World AMPLE ANSWER EXAMPLE ANSWER EXAMPL ANSWExplanation / Answer
The variable n is per thread. It is not a shared variable. The compiler stores the local variable on the stack of each individual thread
The minimum number of times the main thread enters waiting state is 1. This is when all the threads are created but not executed, then they execute (during which main will wait) and then they join with the main thread.
The maximum number of times the main has to wait is 10. This happens when each thread interrupts main to execute when the main program is creating other threads.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.