Hardware Synchronization
Notes
- This is 6.4 of the book.
- In general, software solutions are insufficient in multiprocessor/multi-core environments.
- So the hardware needs to provide a solution.
- The basic idea is we test a variable, if it is true, we can enter the critical section, if not we wait
-
A flag = true ... B while (!flag); C flag = false; D critical section; E flag = true; - The problem is, between lines B and C we could be interrupted and some other process/thread could change the state of
flag
-
- To fix this, modern architectures implement atomic instructions
- This is either a single instruction
- Or a instruction that accomplishes several tasks, but is not interruptable.
- On the X86 there are several that meet this requirement
-
xchg rx, memis one form- This does (atomically)
-
mov tmp, [mem] mov [mem], rx mov rx, tmp
-
- This does (atomically)
- We can also use
lockto make some more complex instructions atomic.-
cmpxchg r/m, rx tmp = dest if ra == rx zf = 1 dest = src else zf = 0 ra = tmp dest = tmp
-
-
- An easy, but ineffective locking mechanism is a spin lock.
- There are better versions of spinlocks, but none are great.
- And working at the assembly level is never outstanding.
- At the OS level we can implement things more effectively using hardware.