I say that the easiest way to think about locking is to use atomic exchange instructions. The following gets an X lock.
LOCK:
set RegisterA = 1
Atomic_Exchange (X, RegisterA) // runs such that no other thread can work with X
if RegisterA == 1:
Means X was 1 when I esecuted the exchange thus someone else has the lock
Since I do not have the lock, goto LOCK
else:
If A is zero, it means I was the first one to set X to 1, which means I own the lock
UNLOCK:
X = 0
Atomic exchange exists on most computers. Intel x86 has an EXCHG instruction for this. Just FYI, Intel x86 also has a comparison and exchange instruction that takes care of the acquisition as well as the comparison for you. Basically, instead of doing an exchange first and then doing a test in software, it uses hardware and only exchanges if X == 0 for starters. This saves the extra write of the X variable, which reduces cache skips for X, which leads to better performance.
source share