master-degree-notes/Concurrent Systems/notes/Lezione2.md

1 KiB

Peterson's algorithm cost O(n^2) A first way to reduce this cost is by using a tournament of MUTEX between pairs of processes: !Pasted image 20250304082459.png

Of course this is a binary tree, and the height of a binary tree is logaritmic to the number of leaves. A process then wins after \lceil \log_{2}n \rceil competitions \to O(\log n) cost.

But we can do better. Let's see an idea of a constant-time algorithm.

Initialize Y at ⊥, X at any value (e.g., 0)

lock(i) :=
	x <- i
	if Y != ⊥ then FAIL
	else Y <- i
	if X = i then return
	else FAIL

 unlock(i) :=
	 Y <- ⊥
	 return

Problems:

  • we don't want the FAIL
  • it is possible to have an execution where nobody accesses its CS, if repeated forever it entails a deadlock
Initialize Y at ⊥, X at any value (e.g., 0)


lock(i) :=
	* FLAG[i] <- up
	X <- i
	if Y ≠ ⊥ then FLAG[i] <- down
		wait Y = ⊥
		goto *
	else Y <- i
	if X = i then return
	else FLAG[i] <- down
	∀j.wait FLAG[j] = down
	if Y = i then return
	else wait Y = 1
	goto *