# Thread: Explanation of Code

1. ## Explanation of Code

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) &#37; 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)```

2. Is this all the code, you are missing some stuff. Also the last line ends the do and should just contain the '}'. Where is turn assigned a value? j = turn; just reserves a space in memory and does not guarantee an initial value of 0. try declaring turn similar to the following:
Code:
`int turn = 0;`
Also, what parts do you understand? mabye a debugger or deskchecking it might help...

3. Code:
`         flag[i] - want_in;`
This is probably a typo: It doesn't do anything [well, in theory, it calculates flag[i] - want_in and then throws away the result - but that is "doing nothing"].

--
Mats

Popular pages Recent additions