The Art of Multiprocess Programming is great, but occasionally you find an explanation which is needlessly complex. I hope this clarifies things Use this example execution and graphic alongside the code to better understand the filter lock. If you have any questions or are confused, feel free to reach out to me.
First, here's the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
|
Example Execution
Suppose we have a filter lock for 4 threads. If a single thread wants to acquire the lock then the process is simple. Let this thread be Thread 0.
- Sets
level[0] = 1
- Sets
victim[1] = 0
- The while loop immediately breaks since no threads exist at a higher level
- Repeat steps 1-3 until the thread exits the for loop.
- The thread has acquired the lock, State at this point:
level[0] = 3
andvictim
array is all zeros since nothing has reset it.
Suppose a second thread wants to acquire the lock. Let this thread be Thread 1.
- Sets
level[1] = 0
- Sets
victim[0] = 1
- The
while
loop holds because the conditionlevel[k] >= i
is true fork=0
, and no one has changed the victim at level 0. This halts Thread 1's progress.
Suppose a third thread wants to acquire the lock. Let this thread be Thread 2.
- Sets
level[2] = 0
- Sets
victim[0] = 2
- ...
HOLD UP!
Thread 1 breaks out of the while
loop. victim[0] == 1
is no longer true.
Thread 1 passes to the next step of the for loop and does the following:
- Sets
level[1] = 1
- Sets
victim[1] = 0
- The
while
loop holds because the conditionlevel[k] >= i
is still true fork=0
and nowvictim[1] = 0
is true until something changes.
BACK TO THREAD 2
- Thread 3 spins on the while loop because the condition
level[k] >= i
is true for bothk=0
andk=1
(only one is necessary), andvictim[0] = 1
To be continued...
Explanatory Graphic
Finally, here's the graphic. It's pretty big, so feel free to open it in another window.