Process Synchronization: Critical Section Problem, Semaphores & Monitors
Overview: Two threads can both read a balance of 100 and then each write 110, losing one increment.
What is Process Synchronization & Race Condition?
- In a multiprogramming or multiprocessing operating system, multiple Cooperating Processes often execute concurrently and **share common…
- What is a Race Condition?
- What is Process Synchronization?
- Imagine IRCTC Tatkal Train Booking where only 1 Lower Berth seat (
availableSeats = 1) is left.
The Critical Section Problem
- A Critical Section (CS) is the specific segment of code inside a process where shared resources (shared variables, files, or tables) are…
- Exit Section Releases the lock so other waiting processes can enter
- Remainder Section All remaining non-shared code of the process
- The 3 Mandatory Requirements for Any Solution to the Critical Section Problem: Any valid synchronization algorithm (like Peterson’s Solution or Semaphores) MUST satisfy all 3 of these conditions:
- Mutual Exclusion (Mandatory):
- Progress (No Unnecessary Delay):
- Bounded Waiting (No Starvation):
View diagram · Figure 3.1: Structure of a Process Entering and Exiting a Critical Section
Semaphores in Operating Systems
- Proposed by Dutch computer scientist **Edsger W.
- Two Types of Semaphores: Binary vs Counting Semaphore: A counting semaphore tracks several available permits and a binary semaphore tracks one.
- 1. Allowed Values: Can take only two values:
0and1. - 2. Initial Value: Initialized to
1. - 3. Primary Use: Used for Mutual Exclusion (protecting a Critical Section).
- 4. Processes Allowed: Allows at most 1 process at a time.
View diagram · Figure 3.2: Binary Semaphore (Mutex) vs Counting Semaphore
Monitors (High-Level Synchronization Construct)
- Why Were Monitors Invented?: While Semaphores are powerful, a small human programming mistake in using them causes catastrophic bugs:
- If a programmer accidentally writes
signal(S)beforewait(S), two processes enter the Critical Section simultaneously (**Mutual… - If a programmer writes
wait(S)twice by mistake (`wait(S)… - What is a Monitor?: Invented by **C.A.R.
- Shared Variables (Private Data)
- Procedures / Methods that operate on those variables
- Initialization Code and Condition Variables (
wait()andsignal()) - Key Advantage of a Monitor: The compiler automatically guarantees that only ONE process can be active inside the Monitor at any given time!
Deadlock: Definition, Characterization, Necessary Conditions & Resource Allocation Graph
Overview: Two programs each hold a printer-related lock and wait for the other’s lock.
What is a Deadlock? (Definition)
- In a multiprogramming environment, several processes compete for a finite number of resources (such as Printers, Tape Drives, Files, or Database…
-
- Example 1 (Narrow Single-Lane Bridge): Two cars approach each other from opposite ends on a narrow one-lane bridge.
-
- Example 2 (Computer Resources):
-
- Process P1 is holding the Printer (R1) and is waiting for the Scanner (R2).
-
- Process P2 is holding the Scanner (R2) and is waiting for the Printer (R1).
- Both P1 and P2 wait for each other forever!
- Normal Sequence of Resource Use by a Process: Under normal operation, a process uses a resource in 3 steps:
- Request: The process requests the resource.
Deadlock Characterization: The 4 Necessary and Sufficient Conditions
- A deadlock situation can arise in an Operating System if and only if all FOUR of the following conditions hold simultaneously in the system…
- 1. Mutual Exclusion: At least one resource must be held in a non-shareable mode—meaning only ONE process can use the resource at any given time.
- If another process requests that resource, the requesting process must be delayed until the resource has been released (e.g., a Printer…
- 2. Hold and Wait: A process must be currently holding at least one resource and simultaneously waiting to acquire additional resources that are…
- 3. No Preemption: Resources cannot be preempted (forcibly taken away) from a process by the OS.
- A resource can be released only voluntarily by the process holding it, after that process has completed its task.
- 4. Circular Wait: A closed circular chain of waiting processes {P0, P1, P2, …, Pn} must exist such that:
- P0 is waiting for a resource held by P1,
View diagram · Figure 3.4: The 4 Necessary Conditions for Deadlock (All 4 Must Hold Simultaneously)
Resource-Allocation Graph (RAG)
- Deadlocks can be described and detected visually using a directed graph called a System Resource-Allocation Graph (RAG).
- Components of a Resource-Allocation Graph: Two Types of Vertices (Nodes):
- Process Nodes (P = {P1, P2, …}): Drawn as Circles (○).
- Resource Nodes (R = {R1, R2, …}): Drawn as Rectangles (□).
- Two Types of Directed Edges (Arrows):
- Request Edge (Pi → Rj): An arrow pointing from Process Pi to Resource Rj.
- Assignment Edge (Rj → Pi): An arrow pointing from Resource Rj to Process Pi.
- Golden Rules of Cycle Detection in RAG: If the Resource-Allocation Graph contains NO cycles:
View diagram · Figure 3.5: Vertices and Edges in a Resource-Allocation Graph (RAG)
Deadlock Handling Approaches: Deadlock Prevention & Avoidance (Banker’s Algorithm)
Overview: Prevention can require programs to request locks in one agreed order, breaking circular wait.
Overview of the 4 Approaches to Handling Deadlocks
- An Operating System can deal with the Deadlock problem in four ways:
- 1. Deadlock Prevention Design rules so at least ONE of the 4 necessary conditions can never hold
- 2. Deadlock Avoidance Check every request dynamically (Banker’s Algorithm) to stay in a Safe State
- 3. Detection & Recovery Allow deadlocks to happen, detect them periodically, and recover
- 4. Deadlock Ignorance Ostrich Algorithm — Ignore rare deadlocks (Used by Windows & Linux for speed!)
View diagram · Figure 3.6: The 4 Deadlock Handling Approaches in Operating Systems
Approach 1: Deadlock Prevention
- We know that all 4 Coffman conditions (Mutual Exclusion, Hold and Wait, No Preemption, Circular Wait) must hold simultaneously for a…
- 1. Eliminating Mutual Exclusion: For Shareable Resources: Read-only files can be shared simultaneously by 100 processes without locks, so they never cause deadlocks.
- For Non-Shareable Resources: Hardware like a Printer or Mutex Lock is inherently non-shareable—we cannot eliminate Mutual Exclusion for such…
- 2. Eliminating Hold and Wait: To ensure that a process never holds one resource while waiting for another, we enforce one of two protocols:
- Protocol A (All-at-Once Allocation): Every process must request and be allocated ALL of its required resources before it begins execution!
- Protocol B (Release Before Request): A process is allowed to request new resources only when it is currently holding ZERO resources (it must release all…
- Drawback: Low resource utilization and potential starvation.
- 3. Eliminating No Preemption (Allowing Preemption): If a process that is already holding some resources requests another resource that cannot be immediately allocated to it,…
Approach 2: Deadlock Avoidance
- While Deadlock Prevention imposes strict static rules that reduce hardware utilization, Deadlock Avoidance is smarter and dynamic:
- Core Requirement: Each process must declare in advance the Maximum Number of resources of each type that it may ever need during its…
- Whenever a process requests a resource at runtime, the Deadlock Avoidance algorithm inspects the current allocation and future maximum…
- If Safe: The resource is granted immediately!
- If Unsafe: The process must wait, even if the resource is currently free!
- Safe State vs Unsafe State: Safe State: A state is Safe if the OS can find at least one Safe Sequence of processes < P1, P2, …, Pn > such that every…
- Key Rule:
- A Safe State has ZERO chance of Deadlock.
View diagram · Figure 3.7: Safe State, Unsafe State, and Deadlock State Spaces
Dijkstra’s Banker’s Algorithm (For Multiple Resource Instances)
- Why is it called the Banker’s Algorithm?
- 4 Data Structures Used in Banker’s Algorithm (n Processes, m Resources):
Available[m]: Number of currently free/available instances of each resource type. Max[n][m]: Maximum demand of each process.Allocation[n][m]: Number of resources currently allocated to each process.Need[n][m]: Remaining resources each process might still need to finish!- Formula: Need[i] = Max[i] − Allocation[i]
- Solved Numerical Example of Banker’s Algorithm (Exam Favorite!): Suppose a system has 3 processes (P0, P1, P2) and 1 resource type with 10 total instances.
- P0: 8
Deadlock Detection and Recovery Techniques in Operating Systems
Overview: Detection lets the system reach a deadlock and then look for evidence such as a cycle in a single-instance wait-for graph.
What is the Deadlock Detection and Recovery Approach?
- If an Operating System does neither Deadlock Prevention nor Deadlock Avoidance, then a Deadlock may eventually occur in the system.
- Deadlock Detection Algorithm: Periodically examines the state of the system to determine whether a deadlock has occurred (and which specific processes and…
- Deadlock Recovery Algorithm: Once a deadlock is detected, executes a recovery mechanism to break the deadlock and restore normal system operation.
Deadlock Detection Techniques
- How the OS detects a deadlock depends on whether each resource type has a Single Instance or Multiple Instances:
- Case 1: Single Instance of Each Resource Type (Wait-For Graph): If all resources have only 1 instance (e.g., 1 Printer, 1 Scanner, 1 Plotter), we can simplify the Resource-Allocation Graph into a…
- If Pi → Rq (Pi is waiting for Rq) and Rq → Pj (Rq is held by Pj), we draw a direct arrow Pi → Pj (meaning **“Process Pi is waiting for…
- Detection Rule: The OS periodically runs a cycle-detection algorithm on the Wait-For Graph.
- Case 2: Multiple Instances of Each Resource Type: When resource types have multiple instances, a Wait-For Graph cannot be used.
Available: Vector of length m indicating available resources.Allocation: Matrix defining resources currently allocated to each process.Request: Matrix defining the current request of each process (instead of lifetimeMaxneed!).
View diagram · Figure 3.8: Two Methods of Deadlock Detection in Operating Systems
Recovery from Deadlock
- Once the Detection Algorithm discovers that a deadlock exists, how does the Operating System break the deadlock?
- Process Termination (Killing Deadlocked Processes)
- Resource Preemption (Snatching Resources Away)
- Method 1A: Abort ALL Deadlocked Processes Instantly breaks the deadlock cycle, but loses all partial work done by every process!
- Method 1B: Abort ONE Process at a Time Kills 1 process, re-runs detection to see if cycle is broken, repeats until deadlock is gone
- Method 2: Resource Preemption Temporarily takes resources from a Victim process, rolls it back, and gives resources to others
- Method 1: Process Termination (Killing Processes): To eliminate the deadlock by terminating processes, the OS uses one of two strategies:
- Abort ALL Deadlocked Processes:
View diagram · Figure 3.9: The Two Methods of Automatic Deadlock Recovery