chapter 28: locks Flashcards
what are the 2 states of a lock?
available or acquired
where are locks usually?
at the beginning of a critical section so only one thread can enter at a time
what do pthread locks use?
mutex - mutual exclusion
what is a coarse-grained locking strategy?
just one big lock surround CS
what is a fine-grained locking strategy?
different locks to protect different data structures.
what help do we need to build a lock?
hardware help
what is the criteria for a lock?
mutual exclusion
fairness - avoid starvation. fair shot at acquiring lock
performance
1st solution: controlling interrupts
lock : disable interrupt
unlock: enable interrupt
positives: it’s simple
negatives:
- allows any thread to perform privileged operations (greedy program calls lock and monopolize the CPU)
OS never regains control and has to restart
- does not work on multiprocessors
- turning off interrupts can cause lost of interrupts which can lead to problems
- inefficient
what is Test and Set (Atomic exchange) (TAS)?
this is hardware support. test and set instruction aka atomic exchange.
first attempt: a simple flag
using a simple flag to implement lock and unlock
flag is 1, lock is held
flag is 0, lock isnt held
if flag is 1 then spin-wait until it hits 0
what is the problem with simple flag approach?
one is correctness, with timely interrupts, we can easily produce both a case where both threads set the flag to 1 and both threads are able to enter CS. failed mutual exclusion.
two is performance, spin waiting wastes time
using Test and Set to create working spin lock
just like simple flag but it works because it is atomic thanks to TAS. spin lock is the simplest type of lock to build, to work correctly, it requires a preemptive scheduler(a scheduler that interrupts via a timer)
evaluating spin locks, how good are they?
correctness: good. it implements mutual exclusion
fairness: may lead to starvation
performance: single CPU - horrible
multiple CPUs - works reasonably well
what is compare and swap (CAS)?
another hardware support for atomic instruction
CAS is more powerful than TAS. however, making simple spin lock with it will be the same as TAS.
if actual ptr == expected
ptr = new
return actual
what is Load-linked and Store-Conditional
a pair of instructions to help build critical sections.
Load linked just loads instruction.
key difference is Store-Conditional which only succeeds if no intervening store to the address has taken place.
On success, returns 1 and updates ptr to value
On Failure, returns 0 and not updated.