Mutex

Inherits: Reference < Object

A synchronization mutex (mutual exclusion).

Description

A synchronization mutex (mutual exclusion). This is used to synchronize multiple Threads, and is equivalent to a binary Semaphore. It guarantees that only one thread can ever acquire the lock at a time. A mutex can be used to protect a critical section; however, be careful to avoid deadlocks.

It's of the recursive kind, so it can be locked multiple times by one thread, provided it also unlocks it as many times.

Warning:

To guarantee that the operating system is able to perform proper cleanup (no crashes, no deadlocks), these conditions must be met:

  • By the time a Mutex's reference count reaches zero and therefore it is destroyed, no threads (including the one on which the destruction will happen) must have it locked.

  • By the time a Thread's reference count reaches zero and therefore it is destroyed, it must not have any mutex locked.

Tutorials

Methods

void

lock ( )

Error

try_lock ( )

void

unlock ( )


Method Descriptions

void lock ( )

Locks this Mutex, blocks until it is unlocked by the current owner.

Note: This function returns without blocking if the thread already has ownership of the mutex.


Error try_lock ( )

Tries locking this Mutex, but does not block. Returns @GlobalScope.OK on success, @GlobalScope.ERR_BUSY otherwise.

Note: This function returns @GlobalScope.OK if the thread already has ownership of the mutex.


void unlock ( )

Unlocks this Mutex, leaving it to other threads.

Note: If a thread called lock or try_lock multiple times while already having ownership of the mutex, it must also call unlock the same number of times in order to unlock it correctly.

Warning: Calling unlock more times that lock on a given thread, thus ending up trying to unlock a non-locked mutex, is wrong and may causes crashes or deadlocks.