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;
}
}
}
非原創(chuàng),當(dāng)時(shí)記錄到本地陆赋,突然想起來(lái)就發(fā)出來(lái)了肥照,侵刪。