Concurrency - Mutual Exclusion
CommentMutual Exclusion
Reasoning about concurrent computation is mostly about time. Reason about complicated conditions involving how multiple time intervals can overlap, or, sometimes, how they cannot.
A thread is a state machine, and its state transitions are called events.
Events are instantaneous
j-th occurence of an event a_i: a_i^j
a precedes b: a\to b
The precedence relation “\to” is a total order on events.
Interval I_A =(a_0, a_1), I_B = (b_0, b_1), I_A\to I_B if a_1\to b_0.
Mutual Exclusion Critical sections of different threads do not overlap. For threads A and B, and integers j and k, either CS_A^k \to CS_B^j or CS_B^j \to CS_A^k.
Freedom from Deadlock If some thread attempts to acquire the lock, then some thread will succeed in acquiring the lock. If thread A calls lock()
but never acquires the lock, then other threads must be completing an infinite number of critical sections.
Freedom from Starvations Every thread that attempts to acquire the lock eventually succeeds. Every call to lock()
eventually returns. This property is sometimes called lockout freedom.
NOTE that starvation freedom implies deadlock freedom.
2.3 2-Thread Solutions
LockOne
1 | class LockOne implements Lock { |
Mutual excluded but deadlock.
LockTwo
1 | class LockTwo implements Lock { |
The Peterson Lock
1 | class Peterson implements Lock { |
Mutual excluded and starvation free
Work for n threads:
The Filter Lock
a direct generalization of Peterson lock to multipe threads
1 | class Filter implements Lock { |
Threads run through levels, until 1 level (CS)
Lamport’s Bakery Algorithm
1 | class Bakery implements Lock { |
lexicographical ordering << (字典序), to break symmetry caused by same label.
In the waiting part, a thread repeatedly rereads the labels one after the other in some arbitrary order until it determines that no thread with a raised flag has a lexicographically smaller label/id pair.
Each thread’s labels are strictly increasing.
本质上就是排队,先到先执行。
Any algorithm that is both deadlock-free and first-come-first-served is also starvation-free.