这是直接从“Herlihy多处理器编程艺术”一书中实现锁定的Bakery算法:
public class Bakery implements Lock {
boolean[] flag;
Label[] label;
public Bakery (int n){
flag = new boolean[n];
label = new Label[n];
for (int i = 0; i<n; i++){
flag[i] = false;
label[i] = 0;
}
}
public void lock(){
int i = ThreadID.get();
flag[i] = true;
label[i] = max(label[0],..., label[n-1]) + 1;
while((∃k!=i)(flag[k] && (label[k], k)<<(label[i], i))){};
}
public void unlock(){
flag[ThreadID.get()]=false;
}
}
正如你在锁定方法中所注意到的那样,虽然有点意义但不完全清楚。所以我从那之前的那一行开始修改那部分:
label[i] = max(label[0],..., label[n-1]) + 1;
while((∃k!=i)(flag[k] && (label[k], k)<<(label[i], i))){};
到目前为止,这是我的版本,但我不确定它是否正确:
public void lock(){
int i = ThreadID.get();
flag[i] = true;
for (int j = 0; j < n; j++)
if (j != i)
while (!(label[j] == 0 || label[i] < label[j] ||
(flag[i] == flag[j] && i < j)))
}
有人能指出我在哪里犯错误吗?提前致谢!