publicvoidlock() { victim = i; // let the other go first while (victim == i) { // Wait for permission } }
publicvoidunlock() { // Nothing to do } }
该算法不能避免死锁,串行执行时会陷入死循环,并发执行时没有死锁。
Peterson's Algorithm
1 2 3 4 5 6 7 8 9 10
publicvoidlock() { flag[i] = true; // Announce I’m interested victim = i; // Defer to the other while (flag[j] && victim == i) { // Wait while other interested & I’m the victim } }
publicvoidunlock() { flag[i] = false; // No longer interested }
classFilterimplementsLock { int[] level; // level[i] for thread i, the level that i is trying to enter int[] victim; // victim[L] for level L, the thread that is excluded from level L
publicvoidlock() { for (intL=1; L < n; L++) { level[i] = L; // Announce intention to enter level L victim[L] = i; // Give priority to anyone but me while ((exists k != i level[k] >= L) &&victim[L] == i ){ // Wait as long as someone else is at same or higher level, and I’m designated victim } } }