Critical Section Problem Explained
- Process Management
- Memory Management
- Deadlocks
- OS Introduction & Fundamentals
- CPU Scheduling Algorithms
- Threads & Concurrency
- Inter-Process Communication (IPC)
- Process Synchronization
- Virtual Memory & Paging
- File Systems
- Disk Scheduling
- I/O Management
Formalizing the Race Condition Problem
As covered in the race conditions note earlier in this section, multiple threads accessing shared data at overlapping times can produce incorrect results. The critical section problem is about designing a solution that guarantees only one thread can execute its critical section - the shared-data-accessing code - at any given moment.
The Three Requirements Any Valid Solution Must Satisfy
| Requirement | What it means |
|---|---|
| Mutual Exclusion | Only one thread can be inside its critical section at a time |
| Progress | If no thread is in its critical section, a waiting thread must eventually be allowed in - no indefinite postponement without reason |
| Bounded Waiting | There must be a limit on how many times other threads can enter before a specific waiting thread gets its turn |
The General Shape of a Critical Section Solution
while (true) {
entry section // request permission to enter
critical section // access the shared data
exit section // release permission
remainder section // everything else, not touching shared data
}Every solution to the critical section problem is really about correctly implementing the entry and exit sections - the code that controls who is currently allowed inside the critical section.
Why a Simple Flag Variable Alone Doesn't Actually Solve This
A naive approach - checking a shared "is anyone in the critical section?" flag before entering - has its own race condition: the check itself and setting the flag afterward aren't a single atomic step, so two threads can both pass the check before either one sets the flag, defeating the entire purpose.
Why Real Solutions Need Hardware or OS-Level Support
Because ordinary code checking-then-setting a flag has this exact same race condition problem it's trying to solve, real solutions rely on either special atomic hardware instructions, or higher-level OS-provided tools - specifically semaphores, mutexes, and monitors, each covered in their own dedicated notes that follow in this section.