class Peterson { // thread-local index, 0 or 1 private var flag:Array[Boolean]{self.rank==1}; private var victim:Int; public def this() { flag = new Array[Boolean](2,false); victim = 0; } public def lock(i:Int) { assert(i == 0 | i == 1); val j:Int = 1 - i; flag(i) = true; // I'm interested victim = i; // you go first while (flag(j) && victim == i) {}; // wait } public def unlock(i:Int) { flag(i) = false; } }