Mutual Exclusion

Alternation

Alternation is a two-thread mutex attempt that uses a shared Last variable: whoever went last must wait. Threads strictly take turns. It breaks rule 3 of the mutual exclusion game — a thread outside its entry/exit code can prevent another thread from entering.

What's wrong with "just take turns"?

Forced alternation couples liveness to participation. If T0 is doing slow non-critical work, T1 can’t re-enter the critical section until T0 comes back and enters again. That violates: “a thread not in entry/exit code must not block others.” Useful as a teaching step on the way to Dekker.

Code

int Last = 0;           // shared
_Task Alternation {
    int me;
    void main() {
        for ( int i = 1; i <= 1000; i += 1 ) {
            while ( ::Last == me ) {}   // entry protocol — wait my turn
            CriticalSection();
            ::Last = me;                // exit protocol — I went last
        }
    }
public:
    Alternation( int me ) : me( me ) {}
};
int main() {
    Alternation t0( 0 ), t1( 1 );
}

Why it fails

Two threads forced to alternate: if T0 is slow outside the critical section, T1 is blocked even though T0 isn’t competing for entry. Rule 3 violation.