Bird
Raised Fist0
Interview Prepoperating-systemsmediumGoogleAmazonFlipkartSwiggy

Critical Section Problem - Requirements & Peterson's Solution

Choose your preparation mode3 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
🎯
Critical Section Problem - Requirements & Peterson's Solution
mediumOSGoogleAmazonFlipkart

Imagine two chefs trying to use the same single stove to cook different dishes simultaneously without burning the food or causing chaos.

💡 Beginners often confuse the critical section problem with general concurrency issues and underestimate the strict requirements needed to avoid race conditions.
📋
Interview Question

Explain the Critical Section Problem, its three key requirements, and how Peterson's solution addresses these requirements for two processes.

Critical Section and Race ConditionMutual Exclusion, Progress, and Bounded Waiting RequirementsPeterson's Algorithm for Two-Process Synchronization
💡
Scenario & Trace
ScenarioTwo processes updating a shared bank account balance concurrently.
Process A reads balance → Process B reads balance → Process A adds deposit → Process B subtracts withdrawal → Process A writes updated balance → Process B writes updated balance → Final balance inconsistent due to race condition.
ScenarioTwo threads printing to the same console output stream.
Thread 1 enters critical section and starts printing → Thread 2 waits until Thread 1 finishes → Thread 1 exits critical section → Thread 2 enters critical section and prints → Output is orderly without interleaving.
  • Both processes attempt to enter the critical section simultaneously → How does Peterson's solution ensure only one enters?
  • One process is delayed or halted indefinitely → Does the other process get blocked forever?
  • Processes repeatedly enter and exit critical sections → How is starvation prevented?
⚠️
Common Mistakes
Confusing mutual exclusion with progress

Interviewer thinks candidate does not understand that mutual exclusion alone is insufficient without progress guarantees.

Clarify that mutual exclusion prevents simultaneous access, but progress ensures no unnecessary waiting.

Assuming Peterson's solution works for more than two processes

Interviewer doubts candidate's knowledge of algorithm limitations.

State explicitly that Peterson's algorithm is designed only for two processes.

Ignoring the role of the 'turn' variable

Interviewer suspects candidate does not grasp how bounded waiting and fairness are enforced.

Explain how 'turn' alternates priority to prevent starvation.

Thinking Peterson's solution requires hardware atomic instructions

Interviewer questions candidate's understanding of software-only synchronization.

Emphasize that Peterson's solution uses only shared memory and simple reads/writes.

🧠
Basic Definition - What It Is
💡 This level covers the fundamental idea and why the problem matters in concurrent programming. Think of it as understanding the rules of a game before playing.

Intuition

The critical section problem ensures that only one process accesses shared resources at a time to prevent conflicts.

Explanation

The critical section problem arises when multiple processes need to access and modify shared data concurrently. Without proper synchronization, race conditions occur, leading to inconsistent or corrupted data. To solve this, three key requirements must be met: mutual exclusion (only one process in the critical section at a time), progress (if no process is in the critical section, one waiting process must be allowed to enter), and bounded waiting (no process should wait indefinitely to enter). Peterson's solution is a classical software-based approach that uses two shared variables to enforce these requirements for two processes, ensuring safe and fair access without hardware support.

Memory Hook

💡 Think of a single-lane bridge where only one car can pass at a time, and a traffic light system (Peterson's solution) controls which car goes next.

Interview Questions

What are the three requirements of the critical section problem?
  • Mutual exclusion: only one process in critical section
  • Progress: decision to enter critical section made without delay
  • Bounded waiting: no indefinite postponement
Depth Level
Interview Time30 seconds
Depthbasic

Covers the problem definition and key requirements; sufficient for initial screening.

Interview Target: Minimum floor - never go below this

Knowing only this helps pass initial rounds but lacks depth for on-site interviews.

🧠
Mechanism Depth - How It Works
💡 This level explains the internal working of Peterson's solution and how it satisfies all requirements. Imagine two friends politely taking turns to use a shared resource without interrupting each other.

Intuition

Peterson's solution uses two shared variables to coordinate entry and ensure mutual exclusion and fairness between two processes.

Explanation

Peterson's solution uses two shared variables: an array 'flag' indicating each process's desire to enter the critical section, and a 'turn' variable indicating which process's turn it is to enter. When a process wants to enter, it sets its flag to true and sets 'turn' to the other process, then waits while the other process's flag is true and it's the other process's turn. This waiting condition ensures mutual exclusion because both processes cannot be in the critical section simultaneously. Progress is guaranteed because if one process is not interested, the other can proceed immediately. Bounded waiting is ensured because the 'turn' variable alternates, preventing starvation. This software-only solution works without special hardware instructions and is a classic example of synchronization in operating systems.

Memory Hook

💡 Imagine two people politely taking turns to enter a room by raising their hands (flags) and yielding to the other’s turn indicator.

Illustrative Code

flag = [False, False]
turn = 0

def enter_critical_section(process_id):
    other = 1 - process_id
    flag[process_id] = True
    global turn
    turn = other
    while flag[other] and turn == other:
        pass  # busy wait

def leave_critical_section(process_id):
    flag[process_id] = False

# Example usage:
# Process 0 and Process 1 call enter_critical_section before critical section
# and leave_critical_section after finishing.

Interview Questions

How does Peterson's solution ensure mutual exclusion?
  • Both processes set their flags before entering
  • Turn variable forces one to wait if both want to enter
  • Waiting condition blocks simultaneous entry
What happens if one process stops executing while the other is waiting?
  • The waiting process can enter if the stopped process’s flag is false
  • Progress is maintained as long as the other process is not interested
Depth Level
Interview Time2-3 minutes
Depthintermediate

Demonstrates understanding of synchronization mechanics and correctness guarantees.

Interview Target: Target level for FAANG on-sites

Mastering this level distinguishes you from most candidates.

📊
Explanation Depth Levels
💡 Choose depth based on interview stage and company expectations.
LevelInterview TimeSuitable ForRisk
Basic Definition30sScreening call or initial roundsToo shallow for on-site interviews at top tech companies
Mechanism Depth2-3 minutesOn-site interviews at FAANG and similar companiesRequires clear understanding and ability to explain synchronization details
💼
Interview Strategy
💡 Use this guide to structure your explanation clearly and confidently before interviews.

How to Present

Start with a clear definition of the critical section problem and its importance.Explain the three key requirements: mutual exclusion, progress, and bounded waiting.Describe Peterson's solution variables and the waiting condition.Walk through how Peterson's solution satisfies each requirement.Mention common edge cases and how the solution handles them.

Time Allocation

Definition: 30s → Example: 1min → Mechanism: 2min → Edge cases: 30s. Total ~4min

What the Interviewer Tests

Interviewer checks if you understand the problem's requirements, can explain the synchronization mechanism, and handle edge cases like simultaneous entry attempts or process delays.

Common Follow-ups

  • What if more than two processes need synchronization? → Peterson's solution is limited to two processes; other algorithms or hardware support needed.
  • How does Peterson's solution compare to hardware-based locks? → Software-only, but less efficient and not suitable for modern multi-core without memory barriers.
💡 These follow-ups test your broader understanding and ability to compare synchronization techniques.
🔍
Pattern Recognition

When to Use

Asked when discussing process synchronization, race conditions, or mutual exclusion in operating systems or concurrent programming interviews.

Signature Phrases

'Explain the critical section problem and its requirements''How does Peterson's solution work?''What happens when two processes try to enter critical section simultaneously?'

NOT This Pattern When

Similar Problems

Practice

(1/5)
1. Trace the sequence of events when a circular wait condition arises among three processes P1, P2, and P3, each holding one resource and waiting for another. What happens next?
easy
A. Each process waits indefinitely because each is holding a resource the next process needs, forming a cycle.
B. One process releases its resource voluntarily, breaking the cycle immediately.
C. The operating system preempts resources from one process to resolve the wait.
D. Processes detect the cycle and terminate themselves automatically.

Solution

  1. Step 1: Identify circular wait

    Each process holds a resource and waits for another held by the next process, forming a cycle.
  2. Step 2: Understand consequences

    Because each process waits for a resource held by another in the cycle, none can proceed, causing indefinite waiting.
  3. Step 3: Analyze other options

    One process releases its resource voluntarily, breaking the cycle immediately assumes voluntary release, which is not guaranteed. The operating system preempts resources from one process to resolve the wait involves preemption, which is not part of the circular wait condition. Processes detect the cycle and terminate themselves automatically assumes automatic termination, which is not standard behavior.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Circular wait leads to indefinite blocking without external intervention.
Hint: Circular wait means processes wait in a cycle, causing indefinite blocking [OK]
Common Mistakes:
  • Assuming processes will release resources voluntarily
  • Confusing circular wait with preemption or automatic recovery
2. You are designing a web server that must handle thousands of simultaneous client requests efficiently. Which approach is most suitable to maximize resource sharing and minimize overhead?
easy
A. Use multiple threads within a single process to handle client requests concurrently
B. Use multiple processes with shared memory segments for communication
C. Use a single-threaded process with blocking I/O for all requests
D. Use multiple processes, each handling a single client request independently

Solution

  1. Step 1: Understand resource sharing in threads

    Threads within the same process share memory and resources, allowing efficient communication and lower overhead compared to processes.
  2. Step 2: Compare overhead of context switching

    Thread context switching is lighter than process context switching, making threads better for high concurrency.
  3. Step 3: Evaluate options

    Use multiple processes, each handling a single client request independently uses processes, which have higher overhead and less efficient resource sharing. Use a single-threaded process with blocking I/O for all requests is single-threaded and blocks, limiting concurrency. Use multiple processes with shared memory segments for communication adds complexity with shared memory and still has process overhead.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Threads maximize resource sharing and minimize overhead for concurrent tasks [OK]
Hint: Threads share memory; processes isolate resources [OK]
Common Mistakes:
  • Assuming processes are always better for concurrency
  • Ignoring context switching overhead differences
  • Believing shared memory between processes is as simple as threads
3. Which of the following statements about the FIFO page replacement algorithm is INCORRECT?
medium
A. FIFO always evicts the least recently used page
B. FIFO can suffer from Belady's anomaly where increasing frames increases page faults
C. FIFO is simple to implement with a queue data structure
D. FIFO does not consider how frequently or recently a page was accessed

Solution

  1. Step 1: Understand FIFO Eviction Policy

    FIFO evicts the oldest loaded page, not the least recently used.
  2. Step 2: Evaluate Each Option

    FIFO can suffer from Belady's anomaly where increasing frames increases page faults is correct; Belady's anomaly can occur with FIFO.
    FIFO always evicts the least recently used page is incorrect; FIFO does not track recency of use.
    FIFO is simple to implement with a queue data structure is correct; FIFO uses a queue for eviction order.
    FIFO does not consider how frequently or recently a page was accessed is correct; FIFO ignores frequency and recency.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    FIFO evicts by arrival order, not usage recency.
Hint: FIFO evicts oldest loaded page, not least recently used [OK]
Common Mistakes:
  • Confusing FIFO with LRU eviction criteria
  • Assuming FIFO tracks page usage
  • Believing FIFO cannot have anomalies
4. Why is aging used as a technique to prevent starvation, and what is a potential downside of applying aging aggressively?
medium
A. Aging increases priority of waiting processes to prevent starvation but can cause priority inversion if overused.
B. Aging decreases priority of high-priority processes to prevent deadlock but may cause livelock.
C. Aging randomly changes priorities to balance load but can lead to starvation of critical processes.
D. Aging forces processes to release resources periodically but increases overhead significantly.

Solution

  1. Step 1: Understand aging purpose

    Aging gradually increases the priority of waiting processes to ensure they eventually get CPU time, preventing starvation.
  2. Step 2: Identify downside

    Over-aggressive aging can cause priority inversion, where lower-priority processes gain higher priority than intended, disrupting scheduling fairness.
  3. Step 3: Analyze options

    Aging increases priority of waiting processes to prevent starvation but can cause priority inversion if overused correctly states aging's purpose and downside. Aging decreases priority of high-priority processes to prevent deadlock but may cause livelock incorrectly associates aging with deadlock prevention and livelock. Aging randomly changes priorities to balance load but can lead to starvation of critical processes misrepresents aging as random priority changes. Aging forces processes to release resources periodically but increases overhead significantly confuses aging with resource release policies.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Aging = priority boost to prevent starvation, risk of priority inversion.
Hint: Aging = priority boost to avoid starvation, watch for inversion
Common Mistakes:
  • Confusing aging with deadlock prevention
  • Thinking aging randomly changes priorities
5. In a system using priority scheduling with aging to prevent starvation, what unexpected behavior might occur if a process holding a critical resource is preempted by an aged higher-priority process, and how can this be mitigated?
hard
A. Livelock will occur due to continuous priority changes; mitigation involves fixed priorities.
B. Deadlock will occur immediately; mitigation requires disabling aging.
C. Priority inversion may occur, delaying the critical resource release; mitigation involves priority inheritance protocols.
D. Starvation will worsen for low-priority processes; mitigation involves removing aging.

Solution

  1. Step 1: Identify the problem

    When a low-priority process holding a critical resource is preempted by a higher-priority process (due to aging), priority inversion can occur because the resource holder cannot proceed to release the resource.
  2. Step 2: Understand mitigation

    Priority inheritance protocols temporarily raise the priority of the resource-holding process to prevent inversion and reduce blocking time.
  3. Step 3: Analyze options

    Priority inversion may occur, delaying the critical resource release; mitigation involves priority inheritance protocols correctly identifies priority inversion and its mitigation. Deadlock will occur immediately; mitigation requires disabling aging incorrectly claims deadlock occurs immediately and suggests disabling aging, which is not a solution. Livelock will occur due to continuous priority changes; mitigation involves fixed priorities confuses livelock with priority changes. Starvation will worsen for low-priority processes; mitigation involves removing aging incorrectly states starvation worsens and suggests removing aging, which would increase starvation risk.
  4. Final Answer:

    Option C -> Option C
  5. Quick Check:

    Priority inversion + priority inheritance = correct diagnosis and fix.
Hint: Priority inversion = resource holder preempted; fix with inheritance
Common Mistakes:
  • Confusing priority inversion with deadlock
  • Thinking aging always prevents all scheduling issues