Critical Section & Mutual Exclusion in OS Explained With Simple Examples

Operating System Chapter 6 · Shared Resource Airlock
Critical Section & Mutual Exclusion in OS Explained With Simple Examples

A critical section is the part of a process where shared data or a shared resource is accessed or modified. If two processes enter that sensitive part at the same time, the final result can become wrong because their operations may interfere with each other. Mutual exclusion is the rule that allows only one process at a time to execute the critical section for a particular shared resource. This chapter explains race condition, critical-section structure, entry and exit sections, the three requirements of a correct solution, locks, busy waiting, atomic operations, mutexes, semaphores and simple solved examples so you can understand why synchronization is needed before studying Peterson's solution, semaphores and classical concurrency problems.

Critical section Mutual exclusion Race condition Progress Bounded waiting Locks & synchronization
Quick definition

What Is a Critical Section in Operating System?

Critical Section & Mutual Exclusion in OS Explained With Simple Examples

A critical section is a part of a program where a process or thread accesses shared data or a shared resource that must not be modified by multiple executions at the same time.

Suppose two processes are updating the same bank balance. Both processes read and write the same shared value. If their operations overlap in the wrong order, the final balance can become incorrect.

This is why the operating system needs synchronization.

Shared data + concurrent access = possible race condition

If you are not clear about processes and concurrency yet, first revise Process in Operating System: Process Concept, Concurrency & Process Generation.

Pictorial representation

Where Is the Critical Section?

Process P1 / P2 Normal code outside shared-resource access
ENTRY
SECTION
CRITICAL SECTION Shared variable, shared file, printer queue, shared buffer, kernel data
EXIT
SECTION
Remainder Section Other work that does not need the shared resource

The entry section decides whether the process is allowed to enter. The exit section releases the permission or lock. The remainder section contains normal work that does not require exclusive access to the shared resource.

The real problem

What Is a Race Condition?

A race condition happens when the final result depends on the timing or order in which concurrent processes or threads execute shared-data operations.

Consider a shared counter:

counter = 5

Process P1 and Process P2 both want to increase it by 1. A simple increment is not always one indivisible step. Conceptually, it may happen as read, add and write.

Process P1
Read 5
Add 1
Value 6
Write 6
Final 6
Process P2
Read 5
Add 1
Value 6
Write 6
One update lost

The expected result was 7, but the result may become 6 because both processes used the same old value.

Expected: 7 · Possible race result: 6
Core solution idea

What Is Mutual Exclusion?

Mutual exclusion means that only one process or thread at a time is allowed to execute the critical section for the same shared resource.

If P1 is inside the critical section, P2 must wait until P1 leaves. After P1 exits, another waiting process can enter.

Process P1

Requests access to shared counter.

ONE
AT A
TIME

Process P2

Waits while P1 is inside the protected section.

Mutual exclusion = at most one process inside the critical section
Critical-section structure

Entry Section, Critical Section, Exit Section & Remainder Section

Entry SectionRequest permission to enter
Critical SectionAccess shared resource
Exit SectionRelease permission
Remainder SectionDo other work

A common textbook form is:

PartPurpose
Entry SectionChecks or waits until the process can safely enter
Critical SectionReads or changes shared data/resource
Exit SectionReleases lock/permission after shared work finishes
Remainder SectionExecutes code unrelated to the protected shared resource
Three conditions to remember

Requirements of a Correct Critical-Section Solution

A good solution to the critical-section problem should satisfy three important conditions.

1. Mutual Exclusion If one process is inside the critical section, no other process should enter the same critical section at that time.
2. Progress If no process is inside the critical section and some want to enter, the choice of the next process should not be postponed forever.
3. Bounded Waiting After a process requests entry, there should be a limit on how many times other processes can enter before that waiting process gets its turn.
Correct solution = Mutual Exclusion + Progress + Bounded Waiting
Requirement 01

Mutual Exclusion Explained With an Example

Suppose P1 and P2 both want to update a shared file.

Correct behavior

P1 enters first. P2 waits. P1 updates the file and exits. Then P2 enters.

Incorrect behavior

P1 and P2 update the shared file at the same time and the final file state becomes unpredictable.

Mutual exclusion prevents the second situation.

Requirement 02

What Does Progress Mean?

Progress means that if the critical section is free and one or more processes want to enter, the system should eventually decide which waiting process enters next.

A process that is not interested in entering the critical section should not unnecessarily block others forever.

Progress prevents the system from getting stuck even though the shared resource is available.

Requirement 03

What Is Bounded Waiting?

Bounded waiting means a process should not wait forever after requesting access to the critical section.

There must be some limit on how many times other processes are allowed to enter before the waiting process gets its chance.

This requirement helps prevent starvation.

Bounded waiting prevents unlimited overtaking by other processes
How mutual exclusion is implemented

What Is a Lock?

A lock is a synchronization mechanism used to control access to a shared resource.

A simple lock has two basic ideas:

Acquire / Lock

Process requests permission before entering the critical section.

Release / Unlock

Process releases permission after finishing the shared operation.

Conceptually:

acquire lock -> critical section -> release lock
Simple lock problem

Why a Normal Shared Boolean Lock Can Fail

Students sometimes think this is enough:

if lock is free -> set lock -> enter

But if checking the lock and setting the lock are separate operations, two processes can both see “free” before either one changes it.

P1
Check free
Yes
Set lock
Enter
Conflict
P2
Check free
Yes
Set lock
Enter
Conflict

The solution is to use an atomic operation or a correct synchronization algorithm so the “check and change” happens safely.

Atomicity

What Does Atomic Operation Mean?

An atomic operation is treated as one indivisible action: other processes cannot observe it half-completed.

Hardware-supported atomic operations are often used to build locks. Examples include test-and-set and compare-and-swap style operations.

At this stage, remember the main idea: if acquiring the lock is atomic, two processes cannot both successfully acquire the same simple lock at the exact same moment.

Atomic = all-or-nothing from the viewpoint of competing processes
Busy waiting

What Is Busy Waiting?

Busy waiting happens when a process repeatedly checks a condition while waiting instead of giving up the CPU.

For example, a process may keep checking whether a lock becomes free:

while lock is busy -> keep checking

This wastes CPU time if the waiting period is long. A lock that waits by repeatedly checking is often called a spinlock.

When can spinning still be useful?

If the expected wait is extremely short, especially on a multiprocessor system, sleeping and waking a thread may cost more than briefly spinning. But for longer waits, blocking is usually more efficient.

Mutex connection

What Is a Mutex?

A mutex is a mutual-exclusion synchronization object used to ensure that only one thread or process at a time owns access to a protected critical section.

Conceptually, a thread locks the mutex before entering the critical section and unlocks it after leaving.

Mutex free

A process can acquire it and enter the critical section.

Mutex owned

Other processes or threads must wait according to the mutex implementation.

Mutexes are one practical way to provide mutual exclusion. Semaphores, monitors and hardware atomic instructions are other synchronization tools.

Semaphore connection

How Are Semaphores Related to Mutual Exclusion?

A binary semaphore can be used to protect a critical section in a way similar to a mutex.

wait() before critical section -> signal() after critical section

Semaphores are more general than simple mutual exclusion and will be studied separately because they can also coordinate ordering between processes.

The next article should cover Semaphores in OS: Wait, Signal, Test-and-Set & Synchronization in detail.

Software solutions

Can Mutual Exclusion Be Solved Without Special Hardware?

Yes. Classical software algorithms were designed to solve the critical-section problem using shared variables.

Peterson's solutionA famous two-process software solution using intent flags and a turn variable.
Dekker's solutionAn older two-process mutual-exclusion algorithm using flags and turn control.
Bakery-style ideasUse ordering concepts to decide which process should enter next.
Modern practiceOperating systems usually rely on atomic hardware support plus higher-level synchronization primitives.

You do not need the full Peterson or Dekker algorithm inside this chapter. They deserve separate step-by-step articles because students usually need solved execution examples.

Hardware approaches

How Does Hardware Help Mutual Exclusion?

Processors provide atomic instructions that operating systems can use to build safe locks.

Test-and-Set

Atomically reads a lock value and changes it in one indivisible operation.

Compare-and-Swap

Atomically changes a value only if it currently matches an expected value.

On a single-processor kernel, temporarily controlling interrupts can also protect very short kernel critical sections, but this is not a general user-process solution and does not directly solve synchronization across multiple processors.

Interactive example

See the Race Condition With and Without Mutual Exclusion

Two Processes Increment the Same Counter

Initial counter = 5 P1 reads 5 P2 reads 5 P1 calculates 6 P2 calculates 6 P1 writes 6 P2 writes 6 Final counter = 6

Result

Race condition occurs Both processes used the same old value, so one increment was lost. The expected answer was 7.
UNSAFE SHARED ACCESS
Deadlock, starvation and fairness

Does Mutual Exclusion Solve Every Concurrency Problem?

No. Mutual exclusion solves unsafe simultaneous entry into a critical section, but poor synchronization design can still create deadlock, starvation or unnecessary waiting.

DeadlockProcesses may wait forever for resources held by each other.
StarvationA process may repeatedly lose the chance to enter.
Priority inversionA high-priority task may wait because a lower-priority task holds a needed lock.
Lock contentionToo many processes may compete for the same lock and reduce performance.

This is why a complete synchronization solution needs more than just a lock; it also needs fairness, correct ordering and careful resource design.

Real-life examples

Where Do We See Critical Sections in Real Systems?

Bank balanceTwo transactions updating the same account balance.
Ticket bookingTwo users trying to reserve the last seat.
Printer queueSeveral processes adding jobs to one shared queue.
Shared counterMany threads increasing the same statistics value.
File updateTwo processes modifying the same shared file metadata.
Kernel dataMultiple CPU cores updating operating-system data structures.
Critical section vs race condition

Critical Section, Race Condition and Mutual Exclusion: Difference

TermMeaningEasy Memory Line
Critical SectionCode that accesses shared data/resourceSensitive code area
Race ConditionWrong/unpredictable result caused by unsafe execution orderTiming changes result
Mutual ExclusionOnly one execution enters the critical section at a timeOne at a time
SynchronizationGeneral coordination of concurrent processes/threadsControl the order safely
Common mistakes

Common Student Confusions to Avoid

Critical section is code, not the shared variable itselfThe shared resource is used inside the critical section.
Race condition is not guaranteed every timeIt depends on the actual interleaving of concurrent operations.
Mutual exclusion alone is not enoughProgress and bounded waiting are also important.
A normal boolean lock can be unsafeCheck-and-set must be atomic or protected correctly.
Busy waiting uses CPUA spinning process continues executing checks while waiting.
Mutex and semaphore are related but not identicalA semaphore is more general and can also be used for ordering.
Concurrency is not the same as parallelismProcesses can be concurrent even on one CPU.
Deadlock is different from race conditionRace means unsafe interleaving; deadlock means processes cannot move forward.
Exam-ready writing

How to Write Critical Section & Mutual Exclusion in an Exam

2 marks

Definition answer

Define critical section and mutual exclusion in one or two clear lines.

5 marks

Critical-section problem

Explain race condition, entry/critical/exit/remainder sections and the three requirements.

8-10 marks

Complete answer

Add solved counter example, mutual exclusion, atomic operations, busy waiting, mutex/semaphore connection and a diagram.

Fast exam memory trick

M P B = Mutual Exclusion, Progress, Bounded Waiting
Practice

Practice Questions With Short Answers

1. What is a critical section?

A critical section is the part of a program that accesses or modifies shared data or a shared resource.

2. What is mutual exclusion?

Mutual exclusion means only one process or thread at a time can execute the critical section for the same shared resource.

3. What is a race condition?

A race condition occurs when the final result depends on the timing or order of concurrent operations on shared data.

4. What are the four parts around a critical section?

Entry section, critical section, exit section and remainder section.

5. What are the three requirements of a correct critical-section solution?

Mutual exclusion, progress and bounded waiting.

6. What is bounded waiting?

Bounded waiting means a process should not be forced to wait forever after requesting entry to the critical section.

7. What is an atomic operation?

An atomic operation is an indivisible action that other processes cannot observe in a half-completed state.

8. What is busy waiting?

Busy waiting happens when a process repeatedly checks a condition while waiting instead of blocking or giving up the CPU.

9. What is a mutex?

A mutex is a synchronization object used to provide mutual exclusion for a protected critical section.

10. Is mutual exclusion enough to solve every synchronization problem?

No. Correct concurrent systems must also consider progress, bounded waiting, deadlock, starvation and ordering requirements.

60-second revision

One-Minute Revision Sheet

Critical sectionCode that accesses shared data/resource.
Race conditionResult depends on unsafe timing/order.
Mutual exclusionOnly one execution enters at a time.
Entry sectionRequests permission to enter.
Exit sectionReleases permission after shared work.
Remainder sectionCode outside the protected shared work.
ProgressA waiting process should eventually be selected when the section is free.
Bounded waitingNo unlimited waiting/overtaking.
Atomic operationIndivisible operation.
Busy waitingKeep checking while consuming CPU.
MutexLock-like object for mutual exclusion.
SemaphoreGeneral synchronization primitive used for exclusion and coordination.

Final memory line

Critical section is the risky area; mutual exclusion is the one-at-a-time rule that protects it.
Frequently asked questions

Frequently Asked Questions

What is a critical section in OS in simple words?

A critical section is the part of a program where shared data or a shared resource is accessed and therefore needs protection from unsafe simultaneous access.

What is mutual exclusion in Operating System?

Mutual exclusion is the rule that only one process or thread at a time can execute the critical section for the same shared resource.

What are the three conditions for solving the critical-section problem?

The three conditions are mutual exclusion, progress and bounded waiting.

What is the difference between a race condition and a critical section?

A critical section is the sensitive code area that accesses shared data, while a race condition is an incorrect or unpredictable result caused by unsafe concurrent execution.

What is busy waiting?

Busy waiting is when a process repeatedly checks whether a condition has changed instead of blocking and giving up the CPU.

Why is an atomic operation important for locks?

An atomic operation prevents two processes from both observing and changing the same lock state at the same time, which helps build safe mutual exclusion.

Next chapter

What Should You Learn Next?

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Join Telegram Exam updates and free resources