# include <stdio .h> # include \" sthread .h\" static void go( int n); # define
ID: 3594437 • Letter: #
Question
# include <stdio .h>
# include " sthread .h"
static void go( int n);
# define NTHREADS 10
static sthread_t threads [ NTHREADS ];
int main ( int argc , char ** argv )
{
int i;
long exitValue;
for (i = 0; i < NTHREADS ; i ++){
sthread create(&( threads [i ]), &go , i );
}
for (i = 0; i < NTHREADS ; i ++){
long ret = sthread join( threads [i ]);
printf (" Thread %d returned %ld ", i , ret );
}
printf (" Main thread done . ");
return 0;
}
void go( int n)
{
printf (" Hello from thread %d ", n);
sthread exit (100 + n);
}
The procedure main() has local variables such as I and exitValue. Are these variables per thread or shared state? Where does the compiler store these variables' states?
Explanation / Answer
First of all before knowing where these variables stores we have to konw TCB.Here TCB is nothing but Thread control block.After knowing that we have to know basic difference between per thread state and shared state.
TCB(Thread Control Block)
-------------------------
Actually it is data structure which contains thread-specific information which is needed to manage it in the operating system kernel.
Difference between per thread state and shared state
-----------------------------------------------------
Mainly Shared state involves Heap but per-thread state involves stack.Heap for dynamic memory allocation and Stack is used for static memory allocation.This point makes major difference between per-thread state and shared state.
Now let come to our point i.e, The procedure main() has local variables such as I and exitValue. Are these variables per thread or shared state? Where does the compiler store these variables' states?
For above question all of the variables in the program are automatic variables.Actually automatic variables is nothing but a local variable which is allocated and automatically whenever program flow enters and leaves the variable's scope.And similarly deallocated automatically whenever program flow enters and leaves the variable's scope.
Actually the variables are stores in per-thread state.Due to in our program the variables exitValue,i are scoped to the main function, So compiler will allocate memory space on the stack.So it uses per-thread state which is used to store the values for these variables.
Similarly variable n in go() function is a parameter and so variable n also acts as a local variable in the go() function.So each and every time go() function is executed the compiler will allocate space on the stack for the variable n.
So atlast what we can say that local variables such as I and exitValue are per thread state.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.