int turn = 0;This means that only process #0 is allowed to enter its critical region. If process #2, for example, wishes to enter its critical region, it must busywait for the variable to change to 2.
void enterCriticalSection(int myProcessNumber){
while(turn != myProcessNumber){ // While it's not my turn,
// ...busywait.
}
}
Eventually, process #0 enters its critical region, and when it exits, it sets the shared variable to 1.
void leaveCriticalSection(){
turn = (turn + 1) % NUMBER_OF_PROCESSES; // Let the next process have a turn.
}
When process #1 enters its critical region, it sets the variable to 2 when it leaves. Process #2 would still be waiting by this time, and would enter its critical region as soon as the variable goes to 2. If it were the last of the cooperating processes, it would set the variable back to 0 again when it left its critical region.
A few problems with this solution:
Alternation is a 'correct' solution (in that it stops races), but it is not terribly practical.