9

I'm busy looking at the filter lock algorithm for n-thread mutual exclusion and I can't seem to understand line 17 of the code. I understand that it is spinning on a condition but not entirely sure what those conditions are. More specifically what (∃k != me) entails.

1 class Filter implements Lock {
2 int[] level;
3 int[] victim;
4 public Filter(int n) {
5     level = new int[n];
6     victim = new int[n]; // use 1..n-1
7     for (int i = 0; i < n; i++) {
8         level[i] = 0;
9     }
10 }
11 public void lock() {
12     int me = ThreadID.get();
13     for (int i = 1; i < n; i++) { //attempt level 1
14     level[me] = i;
15     victim[i] = me;
16     // spin while conflicts exist
17     while ((∃k != me) (level[k] >= i && victim[i] == me)) {};
18     }
19 }
20 public void unlock() {
21     int me = ThreadID.get();
22     level[me] = 0;
23 }
24 }
Crossman
  • 278
  • 5
  • 18

2 Answers2

10

My reading of

(∃k != me) (level[k] >= i && victim[i] == me)

is "there exists some k other than me such that level[k] >= i && victim[i] == me".

The loop spins until there is no k for which the condition holds.

Here is another way to state the same thing:

boolean conflicts_exist = true;
while (conflicts_exist) {
   conflicts_exist = false;
   for (int k = 1; k < n; k++) {
      if (k != me && level[k] >= i && victim[i] == me) {
         conflicts_exist = true;
         break;
      }
   }
}
NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • I'm just unsure where k comes into it or more specifically where k gets defined – Crossman Nov 11 '13 at 15:28
  • @Crossman: You can think of this as a second-level loop, with `k` being the loop variable. See my edit. Hope this makes things clearer. – NPE Nov 11 '13 at 15:34
  • 3
    Obviously, there is an error in your algorithm. `k` should start from `0` and not `1`. Otherwise, if there are two threads, then thread 2 will never know, that thread 1 is ready to take lock. – Jacobian Mar 27 '16 at 08:19
7

It can be written as:

for (int k = 0; k < n; k++) {
      while ((k != me) && (level[k] >= i && victim[i] == me)) {
           //spin wait
      }
}
kamaci
  • 72,915
  • 69
  • 228
  • 366