Counter
ExampleCounter
ExampleRecall the Counter
object:
public class Counter {
long count = 0;
public long getCount () { return count; }
public void increment () { count++; }
public void reset () { count = 0; }
}
If increment()
is called n
times, count
should be n
When multiple threads increment in parallel, only one incrementation performed!
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 mutal exclusion and deadlock-freedom separately is easy!
Raised flag means my dog is in the yard!
If not, raise flag then let dog out
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.
Raised flag means I want to let my dog out!
Raise flag.
If other flag is down, let dog out!
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
When Scott’s flag is lowered, 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…