FYI, if you haven't seen this yet:
Some minor improvements are possible, but overall it's a piece of art.
Originally developed by Mike Burrows
). If you like learning
synchronization primitives, this one will be a good time investment.
The main design goal I guess is handling all possible usage scenarios
gracefully (i.e. not just readers, or writers, or light contention, or
heavy contention, or few waiters, or thousands of waiters, etc) which
is expected of a primitive used in literally millions of place across
thousands of systems. It also has some interesting features like
contention profiling and deadlock detection. FWIW it also fits into a
single intptr (i.e. 4 bytes on 32-bit systems).
There is also a bit simplified version of the same algo in nsync library:
It's C and does not have contention profiling and deadlock detection,
so may be easier for leaning of the mutex algorithm itself.