I am having trouble seeing what this code is doing. I keep getting flag[i] as the only on going into the critical section, which obviously means I am missing something! This isnt homework and I didn't write this code, we are discussing it in class, but I need a better understanding of what is going on! Please explain! Thanks!
So all elements of flag are initially idle, and inital value of turn is between 0 and n-1 (this is what is throwing me off I think.) The processes share:
Code:
enum pstate {idle, want_int, in_cs};
pstate flag[n];
int turn;
Code:
do {
while(TRUE){
flag[i] - want_in;
j = turn;
while( j != i){
if (flag[j] != idle)
j = turn;
else
j = (j + 1) % n;
}
flag[i] = in_cs;
j = 0;
while ((j<n) && (j == i || flag[j] != in_cs))
j++;
if ((j >=n) && (turn == i || flag[turn] == idle))
break;
}
//critical section
j = (turn + 1) % n;
while (flag[j] == idle)
j = (j + 1) % n;
turn = j;
flag[i]= idle;
//remainder section
} while (TRUE)