>Remember that, in the [[#Correct solution|correct implementation]], there is this line: `wait (FLAG[1-i] = down OR AFTER_YOU != i)`. Thus, to access the critical section (the `return` instruction of the `lock` function), the possibilities are just the two discussed above.
- p at level ℓ can increase its level by writing its FLAG at ℓ+1 and its index in $A_Y[ℓ+1]$
- let $p_x$ be the last one that writes `A_Y[ℓ+1]`, so `A_Y[ℓ+1]=x`
- for $p_x$ to pass at level ℓ+1, it must be that $∀k≠x. F[k] <ℓ+1$,then$p_x$istheonlyprocatlevelℓ+1andthethesisholds,since1<=n-ℓ-1
- otherwise, $p_x$ is blocked in the wait and so we have at most n-ℓ-1 processes at level ℓ+1: those at level ℓ, that by induction are at most n-ℓ, except for px that is blocked in its wait.
##### Starvation freedom proof
**Lemma:** every process at level ℓ ($\leq n-1$) eventually wins $\to$ starvation freedom holds by taking $ℓ=0$.
Reverse induction on ℓ
Base ($ℓ=n-1$): trivial
Induction (true for ℓ+1, to be proved for ℓ):
- Assume a $p_x$ blocked at level ℓ (aka blocked in its ℓ+1-th wait) $\to \exists k\neq x, F[k]\geqℓ+1 \land A\_Y[ℓ+1]=x$
- If some $p_{y}$ will eventually set $A\_Y[ℓ+1]$ to $y$, then $p_x$ will eventually exit from its wait and pass to level ℓ+1
- Otherwise, let $G = \{p_{i}: F[i] \geq ℓ+1\}$ and $L=\{p_{i}:F[i]<ℓ+1\}$
- if $p \in L$, it will never enter its ℓ+1-th loop (as it would write $A_Y[ℓ+1]$ and it will unblock $p_x$, but we are assuming that it is blocked)
- all $p \in G$ will eventually win (by induction) and move to L
- $\to$ eventually, $p_{x}$ will be the only one in its ℓ+1-th loop, with all the other processes at level <ℓ+1
- $\to$ $p_{x}$ will eventually pass to level ℓ+1 and win (by induction)
##### Peterson algorithm cost
- $n$ MRSW registers of $\lceil \log_{2} n\rceil$ bits (FLAG)
- $n-1$ MRMW registers of $\lceil \log_{2}n \rceil$ bits (AFTER_YOU)
- $(n-1)\times(n+2)$ accesses for locking and 1 access for unlocking
It satisfies MUTEX and starvation freedom. It does not satisfy bounded bypass:
- consider 3 processes, one sleeping in its first wait, the others alternating in the CS
- when the first process wakes up, it can pass to level 2 and eventually win
- but the sleep can be arbitrary long and in the meanwhile the other two processes may have entered an unbounded number of CSs