Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

  1. 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
  2. _State ThreadId is initialized to 0
  3. 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
  4. 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 must SetEvent the event handle in order sets _ThreadId to 0 and invokes SetEvent to unblock a thread
  5. 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 

...