Mutexes - aryanjoshi0823/5143-Operating-System GitHub Wiki
A Mutex is a locking mechanism that ensures that only one thread or process can access the critical section at a time. It is a binary object that has two states:
- Locked: A thread is using the shared resource, and others must wait.
- Unlocked: The resource is available for use.
The main goal of a mutex is to solve the Critical Section Problem, ensuring:
- Mutual Exclusion: Only one process accesses the critical section at a time.
- Progress: If no process is in the critical section, others waiting must eventually proceed.
- Bounded Waiting: No process waits indefinitely to access the critical section.
Mutexes typically support the following operations:
- If the mutex is unlocked, the thread/process locks it and proceeds to access the critical section.
- If the mutex is locked, the thread/process is blocked and waits until it becomes available.
- Unlocks the mutex, allowing other threads/processes waiting to acquire it.
- Attempts to lock the mutex without blocking.
- If the mutex is already locked, the operation fails, and the thread continues execution.
Imagine a printer shared between multiple processes. A mutex ensures that only one process prints at a time.
- Process 1 locks the mutex before printing.
- Process 2 tries to lock the mutex but is blocked since Process 1 holds the lock.
- Process 1 finishes printing and unlocks the mutex.
- Process 2 acquires the mutex and begins printing.