A mutex, short for “mutual exclusion”, is arguably the simplest waitable synchronisation construct you can imagine. It exposes methods for acquisition and release, and the semantics are straightforward:
- Initially it isn’t “owned”, and anybody who asks to acquire it is granted ownership
- While owned, anybody else who comes around to try and acquire it must wait her turn
- When the owner is done with it, the mutex is released, which then transfers ownership to one waiter (if any) and unpends that waiter
A mutex can also validly be referred to as a critical section, in the sense that it protects a critical section of code, or more accurately, data. When programming libraries expose both a mutex and a critical section, as Windows does, it really just reflects different implementations of synchronisation objects with the same semantics. You could also consider a spinlock to be a flavour of mutex: while the name “spinlock” describes the mechanism by which competing threads jostle for exclusive ownership (it can’t be politely waited upon), the idea of mutual exclusion with at most one concurrent owner still applies.
SOS_Mutex class layout and interface
This class is directly derived from EventInternal<SuspendQSlock>, with three modifications:
- The addition of an ExclusiveOwner member.
- The override of the Wait() method to implement mutex-specific semantics, although the main act of waiting is still delegated to the base class method.
- The addition of an AddAsOwner() method, called by Wait(), which crowns the ambient task as the exclusive owner after a successful wait.
Continue reading “Unsung SQLOS: the SOS_Mutex”