CXMutex

From cxwiki

The CXMutex class is the most basic form of locking primitive. The object exists in one of two states: LOCKED or UNLOCKED. Any thread may lock the object, after which any further attempt (by any thread, including the lock-owner) to lock it again will block until it has been unlocked. The unlock must be performed by the lock-owner thread.
// Lock the mutex to the current thread. Blocks while any thread still has the mutex locked.
void LockMutex(void) const; 

// Unlocks the mutex from the current thread.
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 CXMutex is UNLOCKED when constructed.
  • The CXMutex should be returned to the UNLOCKED state prior to destruction. It is considered an error for the application to destroy a CXMutex while it is locked, because that would likely to lead to unlock attempts after destruction.
  • An attempt to lock or unlock a CXMutex 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.
  • It is considered an error for the application to attempt to lock a CXMutex on the lock-owner thread. The resultant behaviour is undefined, typically leading to either a deadlock, an assertion, or both.
  • 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 no the lock-owner.

Performance

CXMutex uses the underlying OS mutex support, and typically performs a system call. While not horrifically slow, it is measurably slower on average than a CXSpinLock in any case where the lock is low-contention. CXMutex is well-suited to tasks where locking and unlocking do not occur overly frequently, and where the amount of time spent with the lock held is non-trivial.
 
CXMutex inherits the underlying OS guarantees for mutex fairness.