Today/Wednesday: Mutual Exclusion (pen & paper)
Fix Counter
issue by locking the count
To increment the Counter
:
Counter
is locked
Counter
Counter
public class LockedCounter {
long count = 0;
boolean locked = false;
public long getCount () { return count; }
public void increment () { count++; }
public void reset () { count = 0; }
public void lock (int id) {
while (locked) { }
locked = true;
}
public void unlock () { locked = false; }
public boolean isLocked () { return locked; }
}
public void run () {
for (long i = 0; i < times; i++) {
counter.lock(id);
try {
counter.increment();
}
finally {
counter.unlock();
}
}
LockedCounterTester
Demo!What happened?
public void lock (int id) {
while (locked) { }
locked = true;
}
If multiple threads try to increment at a time:
We want our Counter
to satisfy mutual exclusion.
How can Scott and Will ensure that we don’t let Finn and Ruple out in the yard at the same time?
Safety Goal:
Liveness Goal:
Note: getting mutual exclusion and deadlock-freedom separately is easy!
If not, raise flag then let dog out
Question. Does this work?
We both look at (approximately) the same time and see others’ flag is down.
We both raise flags as (approximately) the same time.
We both let dogs out at the same time.
Raise flag.
If other flag is down, let dog out!
Question. Does this work?
Both raise flag at (approximately) same time.
Both see other’s flag raised.
Both wait… neither dog ever goes outside!
Both protocols are symmetric
Can a symmetric protocol possibly work?
Suppose we act simultaneously:
start in same state
perform same action
see that other performed same action
respond in same manner
…
This continues indefinitely, so either
We need an asymmetric protocol
Note. Symmetry breaking is a common theme in parallel/distributed computing.
Separate protocols for Will and Scott
When Finn needs to go out:
Raise flag
While Scott’s flag is raised, wait
Let Finn out
When Finn comes in, lower flag
When Ru needs to go out:
Raise flag
While Will’s flag is raised:
lower flag
wait until Will’s flag is lowered
raise flag
When Scott’s flag is up and Will’s is down, release Ru
When Ru returns, lower flag
If both Scott and Will:
then at least one of us will see other flag raised
If we want to prove mutual exclusion property
Before letting a dog out, both Scott and Will do:
If both Finn and Ru are in yard at same time, Will or Scott must not have followed the protocol!
If both Finn and Ruple want to go out
This protocol gives mutual exclusion and deadlock-freedom…