------------------------------------------------------------------------------- -- Knuth's mutual exclusion protocol optimized for two processes -- (3 integer variables, complex conditions, starvation-free) ------------------------------------------------------------------------------- module knuth_2 (ARCH_3B) is !nat_bits 2 -- use 2 bits to store natural numbers (* * Process P (i) competing for the access to critical section * where i = 0..1, j = 1 - i * * loop * non critical section ; * loop * A[i] := 1 ; * await B == i or A[j] == 0 ; * A[i] := 2 ; * if A[j] != 2 then * break * end if * end loop ; * B := i ; * critical section ; * B := j ; * A[i] := 0 * end loop *) process P [NCS:Pid, CS:Access, A, B:Operation] (i: Pid) is var j: Pid, a_j, b:Nat in j := 1 - i; loop NCS (i); loop L1 in A (Write, i, 1 of Nat, i); loop L2 in B (Read, ?b, i); if (b == i) then break L2 end if; A (Read, j, ?a_j, i); if (a_j == 0) then break L2 end if end loop; A (Write, i, 2 of Nat, i); A (Read, j, ?a_j, i); if a_j != 2 then break L1 end if end loop; B (Write, Nat (i), i); CS (Enter, i); CS (Leave, i); B (Write, Nat (j), i); A (Write, i, 0 of Nat, i) end loop end var end process ------------------------------------------------------------------------------- process Main [NCS:Pid, CS:Access, A, B:Operation, MU:Latency] is Arch_3b [NCS, CS, A, B, MU] end process end module