CXRecursiveMutex

From cxwiki

The CXRecursiveMutex class is similar to CXMutex but provides support for the lock-owner thread to recursively lock the mutex. The object exists in one of two states: LOCKED or UNLOCKED, with the LOCKED state maintaining a reference count. Any thread may lock the object, after which any further attempt by another thread to lock it again will block until it has been fully unlocked. The unlocks must be performed by the lock-owner thread.
// Lock the mutex to the current thread. Blocks while any other thread still has the mutex locked.
void LockMutex(void) const; 

// Unlocks the mutex from the current thread. Must be called once per call to LockMutex().
void UnlockMutex(void) const;

// Attempts to lock the mutex, but does not block. Returns true if a lock was successfully taken.
bool TryAndLockMutex(void) const;

Restrictions

  • The CXRecursiveMutex is UNLOCKED when constructed.
  • The CXRecursiveMutex should be returned to the UNLOCKED state prior to destruction. It is considered an error for the application to destroy a CXRecursiveMutex while it is locked, because that would likely to lead to unlock attempts after destruction.
  • An attempt to lock or unlock a CXRecursiveMutex during or after its destruction is considered an error. The resultant behaviour is undefined. This includes the scenario where a lock attempt is placed prior to destruction, but cannot be honored until destruction has begun.
  • No attempt is made to detect or recover from deadlocks. It is the callers responsibility to ensure that locks are taken and released in an approriate manner to avoid deadlocks.
  • It is considered an error to attempt to unlock a mutex on a thread which is not the lock-owner.

Performance

CXRecursiveMutex uses the underlying OS mutex support, and typically performs a system call. It may be slower or more resource-intensive than CXMutex.
 
CXRecursiveMutex inherits the underlying OS guarantees for mutex fairness.