Spinlocks and Barrier Synchronization Flashcards
Spinlock
- Each java object has an intrinsic lock
- So far we have dealt with threads that block
awaiting access to a shared resource
(This is implicit using synchronized keyword) - An alternative is to keep the thread active and continuously ‘spinning’ attempting to acquire the lock
This is a spin lock
(Potentially) improves threading performance and CPU usage
An Attempted Spinlock Implementation\
Spinlock execution
Spinlock Solution
Disabling Interrupts
- Pre-emptive context switch only happens when interrupt occurs
- Could disable interrupts to prevent context switch in critical section
While this works, comes with many disadvantages…
1. Interrupts might be disabled frequently and for a long
time
Clock ticks, I/O events could be missed
2. Will not be sufficient when you have more than one processor
* More than once thread could be running concurrently
3. Error proneness
Forgetting to call release_lock() means interrupts disabled forever
Machine Instruction
test-and-set, comp-and-swap, fetch-and-add
- Atomic machine instruction
- Sets variable passed to true,
- Tells if variable was true or false before being set to true
Machine Instruction: test_and_set() lock
Software Only – Peterson’s Algorithm
Assumes atomic reads and writes
- Only works with two threads (can be generalized to n threads)
- Assumes thread ID are 0 and 1
In green and pink are instructions from
processes 0 and 1, respectively
Blocking vs spinning locks
Blocking:
- Scheduler blocks threads while they wait
- Good for long critical sections
- Frequent queue management if locks
accessed frequently
Spinning:
- Sit in a tight loop until lock acquisition
- Good for short critical sections
- Avoid queue management