Please work out these problems before your next discussion section. The GSIs will go over these problems during the discussion section.
Consider the following pseudo-code for a program that executes two threads, each of which executes the thread code give below:
/* Global variables */
int n = 20;
int tally = 0;
/*
* Thread start function
*/
total () {
int count; /* local variable */
for(count = 0; count < n; count++) {
tally = tally + 1;
}
}
/*
* Main function
*/
main() {
tally = 0; /* initializing a global variable */
/*
* First, we create a thread, thread1; it starts executing from the
* function "total", defined above.
*/
Thread thread1 = new Thread(total);
/*
* The call to new Thread returns immediately and we create another thread.
* thread1 starts executing from the function "total", defined above.
*/
Thread thread2 = new Thread(total);
}
Assume that the following operators are atomic: comparision operators, assignment, and addition. Determine the proper lower bound and the upper bound on the final value of the shared variable tally. Also, briefly explain who you arrived at your conclusion.
/* Global variables */ active[0] = false; active[1] = false; turn = 0;
while (1) {
active[0]=true;
while(turn!=0){
while (active[1]) {
}
turn=0;
}
<critical section>
active[0]=false;
<do other stuff>
}
while (1) {
active[1]=true;
while (turn!=1){
while (active[0]) {
}
turn=1;
}
<critical section>
active[1]=false;
<do other stuff>
}
Is this a correct solution? If yes, prove it; else give a counter-example (by showing a possible interleaving of threads that allow the two threads to simultaneously access their critical sections).