class Lock {
private int turn = 0;
public void acquire(int tid) {
while (turn == (1 - tid));
}
public void release(int tid) {
turn = (1 - tid);
}
}
- Yes, guarantees mutual exclusion; only the thread with tid matching
turn is able to acquire the lock.
- No, does not guarantee progress; if thread 0 never tries to acquire
the lock (it is executing other code), thread 1 will not be able to
acquire the lock.
- Limitations (Not required): Only works with two processes, uses busy waiting.
|
class Lock {
public void acquire() {
disableInterrupts();
}
public void release() {
enableInterrupts();
}
}
- Guarantees mutual exclusion on a uniprocessor, but not on a
multiprocessor. On a uniprocessor, once the timer interrupt is
disabled, the scheduler won't be able to switch to another process
(assuming the scheduled process doesn't voluntarily relinquish the
CPU). However, on a multiprocessor, it is possible for the other CPU to be
running a process that also acquires the lock.
- Yes, guarantees progress; once a process is scheduled, it is able to
acquire the lock without incident.
- Limitations: Only works on uniprocessors; allows user processes
to disable interrupts for an arbitrary long period; cannot service
other important interrupts during critical section (e.g., I/O); cannot schedule
any other processes when lock is held, even those not contending for
the lock.
|
class Lock {
private int turn = 0;
private boolean lock[2] = {false, false};
public void acquire(int tid) {
lock[tid] = true;
turn = 1 - tid;
while (lock[1-tid] && turn == (1 - tid));
}
public void release(int tid) {
lock[tid] = false;
}
}
This is the solution presented in class.
- Yes, guarantees mutual exclusion.
- Yes, guarantees progress.
- Limitations: Only works for two threads; involves busy-waiting.
|
class Lock {
private boolean lock = true;
public void acquire() {
while (TestAndSet(lock, true);
}
public void release() {
lock = false;
}
}
Note that the lock was initialized to the wrong value.
- Yes, guarantees mutual exclusion. It is not possible for more than
one process to acquire the lock.
- No, does not guarantee progress. No process is able to acquire the
lock, since it is initialized to true, designating that the
lock is already acquired.
- Limitations: Not needed.
|