1.不行
if (!lock) {
if (!lock) {
lock = true;
// critical section
lock = false;
}
Context switch after the
testing and before the
locking
2.不行,直接跳过了了某一个的临界区
Lock before testing? How?
lockA = true; lockB = true;
if (!lockB) { if (!lockA) {
// critical section // critical section
} }
lockA = false; lockB = false;
Context switch after the locking and before the testing
3 不行
Lock before testing? How?
lockA = true; lockB = true;
while (lockB); //X if (!lockA) { //Y
// critical section /* critical section */}
lockA = false; lockB = false;
It works!
at X: if B is not locked, enter CS; otherwise wait;
at Y: if A is not locked, enter CS; otherwise leave
Not symmetric!
4 可以
Peterson’s algorithm
while (true) {
lock[i] = true;
turn = j;
while (lock[j] && turn == j);
// critical section
lock[i] = false;
// remain section
}
It works, but rathercomplicated!