Computer OS: Following is the code for two threads T1 and T2: [executed once] in
ID: 3682975 • Letter: C
Question
Computer OS:
Following is the code for two threads
T1 and T2: [executed once]
int x = 0 // global shared variable
T1: for (i=0; i++; i<100) x++;
T2: x++ // no loop, just one increment
The above code was given to students with the question “what is the final value of x, after both T1 and T2 finished executing.”
Everyone answered by saying the value would be 100 or 101.
One student answered, the value can be anything from 1 to 101. This person was right.
Show how this is possible (Hint: Show how it can be 1).
Following is the code for two threads T1 and T2: [executed once] int x = 0 // global shared variable T1: for (1-0; i++; iExplanation / Answer
The thread T1 will never execute because the loop matching condition is i++ and the value of i is 0. The value 0 is considered as false, so the loop will never execute.
After checking for the thread T1 the thread 2 will execute and after the execution of thread T2 the value of x will be 1.
Since, each thread will try to execute only once thus thread T2 will execute and when thread T1 will execute the loop condition is false, so the loop body will never execute.
Thus, the value will be 1.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.