...
- Every mutex has two members, _WaitEvHandle, which is a automatic reset Win32 event handle used for blocking, and _ThreadId, the ID of the current thread
- _State ThreadId is initialized to 0
- To lock,
mtx_lock
calls InterlockedIncrement InterlockedCompareExchange on _StateThreadId. If the return value is 0, we successfully locked the mutex. If it is not 0, then we must block, so go ahead and block on the event handle - To unlock,
mtx_unlock
calls InterlockedDecrement on _State. If the return value is -1, nobody was waiting and we can return without touching the kernel; otherwise, we mustSetEvent
the event handle in order sets _ThreadId to 0 and invokes SetEvent to unblock a thread - Note that at no point once someone has blocked on the mutex will the _State member return to -1 until all threads blocked on the mutex
...