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:

  1. Locked: A thread is using the shared resource, and others must wait.
  2. Unlocked: The resource is available for use.

Purpose of Mutex

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.

Mutex Operations

Mutexes typically support the following operations:

1. Lock (Acquire)

  • 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.

2. Unlock (Release)

  • Unlocks the mutex, allowing other threads/processes waiting to acquire it.

3. Try Lock (Optional)

  • Attempts to lock the mutex without blocking.
  • If the mutex is already locked, the operation fails, and the thread continues execution.

Example: Mutex Workflow

Scenario:

Imagine a printer shared between multiple processes. A mutex ensures that only one process prints at a time.

Workflow:

  1. Process 1 locks the mutex before printing.
  2. Process 2 tries to lock the mutex but is blocked since Process 1 holds the lock.
  3. Process 1 finishes printing and unlocks the mutex.
  4. Process 2 acquires the mutex and begins printing.
⚠️ **GitHub.com Fallback** ⚠️