Advanced Computer Architecture Chapter 7.55
User Level Synchronization—Operation Using this Primitive
Spin locks: processor continuously tries to acquire, spinning around a loop trying to get the lock
li R2,#1
lockit: exch R2,0(R1) ;atomic exchange
bnez R2,lockit ;already locked?
What about MP with cache coherency?
Want to spin on cache copy to avoid full memory latency
Likely to get cache hits for such variables
Problem: exchange includes a write, which invalidates all other copies; this generates considerable bus traffic
Solution: start by simply repeatedly reading the variable; when it changes, then try exchange (“test and test&set”):
• try: li R2,#1
lockit: lw R3,0(R1) ;load var
bnez R3,lockit ;not free=>spin
exch R2,0(R1) ;atomic exchange
bnez R2,try ;already locked?