Operating Systems: Process Synchronization, Semaphores & Deadlock Prevention
Operating Systems (OS) is a core Computer Science subject tested rigorously in technical placement interviews and graduate engineering exams. Understanding how the kernel manages concurrency and avoids deadlocks is vital for building reliable software.
1. The Critical Section Problem
When multiple threads or processes access shared memory concurrently, race conditions can produce inconsistent data.
3 Requirements for a Valid Solution:
- Mutual Exclusion: If process
Pis executing in its critical section, no other process can enter. - Progress: If no process is in its critical section, selection of the next process cannot be postponed indefinitely.
- Bounded Waiting: There must be a limit on the number of times other processes can enter their critical sections before a requesting process is granted entry.
2. Mutex vs Semaphore
- Mutex (Mutual Exclusion Lock): A locking mechanism where only the thread that acquired the lock can release it (Ownership semantics).
- Counting Semaphore: A synchronization tool initialized to an integer
N, allowing up toNconcurrent processes to access a shared pool of resources.
3. Deadlocks & The 4 Coffman Conditions
A deadlock occurs when a set of processes are blocked because each process is holding a resource and waiting for another resource held by someone else.
All 4 conditions must hold simultaneously for a deadlock to exist:
- Mutual Exclusion: At least one resource is held in a non-shareable mode.
- Hold and Wait: A process is holding at least one resource and waiting to acquire additional resources.
- No Preemption: Resources cannot be forcibly confiscated; they are released only voluntarily.
- Circular Wait: A closed chain of processes exists where
P0waits forP1, andPnwaits forP0.
4. Deadlock Handling Strategies
- Deadlock Prevention: Invalidate at least one of the 4 Coffman conditions (e.g., impose strict global resource ordering to eliminate circular wait).
- Deadlock Avoidance (Banker's Algorithm): Dynamically checks resource allocation state to ensure the system never enters an "Unsafe State".
- Deadlock Detection & Recovery: Allow deadlocks to happen, detect cycles using Resource Allocation Graphs (RAG), and preempt processes or terminate offending tasks.