http://en.wikipedia.org/wiki/Lamport%27s_bakery_algorithm
I have some problems to understand this algorithm. What happens if the current thread and the thread, I am looking at the moment in the for loop are the same?
Threads: 0, 1, 2
Thread 1 takes ticket 1. Thread 2 takes ticket 2. Thread 0 does nothing.
Array = i: 0, 1, 2
Round 1:
- Thread 1 (j=0): Array[0] = 0. next.
- Thread 2 (j=0): Array[0] = 0. next.
Round 2:
- Thread 1 (j=1): Array[1] = 1. (1,1) > (1,1)
- Thread 2 (j=1): Array[1] = 1. (1,1) > (2,2)
(1,1) > (1,1) wrong.
(1,1) > (2,2) wrong.
Both threads are waiting…
What’s wrong? Is this a deadlock?
The while loop in the algorithm allows a thread to enter critical section when the inequality does not hold. It says: wait as long as the condition (Number[j] != 0) && ((Number[j], j) < (Number[i], i) is true.
Since (1,1) is not greater than (1,1) the thread 1 can pass the loop and enter the critical section.