class Peterson: public Lock
{
private:
bool flag[2];
int turn;
public:
void lock() {
int i = Thread.getId();// 0 or 1
flag[i] = true;
turn = j;
while(flag[j] && turn == j);
}
void unlock() {
int i = Thread.getId();
flag[i] = false;
}
}
class Bakery: public Lock {
private:
bool flag[];
Label label[];
public:
Bakery (int n) {
flag = new bool[n];
label = new Label[n];
for(int i=0; i<n; i++) {
flag[i] = flase;
label[i] = 0;
}
void Lock() {
int i = Thread.getId();
flag[i] = true;
label[i] = max(label[0], ..., label[n-1]) +1;
while((exist k!=i)(flag[k] && label[k]<label[i])
}
void unlock() {
flag[Thread.getId()] = false;
}
}
}
非原创,当时记录到本地,突然想起来就发出来了,侵删。