Overview
TheMutex class implements a binary mutex (mutual exclusion lock) with a FIFO queue for managing blocked threads. It ensures that only one thread can access a critical section at a time, with fair ordering based on arrival time.
Constructor
Creates a new mutex instance with no initial owner.Initial State:
locked:falseowner:nullqueue:[]
Properties
Indicates whether the critical section is currently taken.
true when a thread owns the mutex.The thread that currently holds the mutex.
null when the mutex is unlocked.FIFO queue of threads waiting to acquire the mutex, ordered by arrival time.
Methods
acquire(thread)
Attempts to acquire the mutex for the specified thread.The thread attempting to acquire the mutex.
true: Thread successfully acquired the mutex and can proceedfalse: Thread is blocked and added to the waiting queue
- Already owns mutex: If the mutex transferred ownership to this thread via
release(), returnstrue - Mutex available: If unlocked, immediately grants ownership and returns
true - Mutex locked: Blocks the thread, sets its state to
"blocked", and adds it to the queue
mutex.js:10
release(thread)
Releases the mutex and transfers ownership to the next waiting thread if the queue is non-empty.The thread releasing the mutex. Must be the current owner.
- Validation: Throws error if the calling thread is not the current owner
- No waiters: Unlocks the mutex and clears the owner
- Has waiters: Directly transfers ownership to the first thread in the queue (FIFO), sets it to
"ready"state
mutex.js:34
Throws:
Error: “Solo el poseedor puede liberar el mutex” if non-owner attempts to release
Usage Example
FIFO Guarantee
The mutex implements strict FIFO ordering:- Threads are added to the queue in arrival order
- When released, ownership transfers to the first thread in the queue
- No thread can skip ahead (prevents starvation)