← Lessons

quiz vs the machine

Silver1040

Concurrency

The Critical Section Problem

Why shared data needs a protected region, and what a correct solution must guarantee.

4 min read · intro · beat Silver to climb

What is a critical section

A critical section is a stretch of code that reads or writes shared state which other threads also touch. If two threads run their critical sections at the same time, updates can interleave and corrupt the data. The classic example is two threads each doing a non atomic increment of a shared counter: both read the same value, both add one, and one update is lost.

The structure of the problem

Each thread cycles through four parts:

  • Entry section where it asks permission to enter
  • Critical section where it touches shared state
  • Exit section where it releases its claim
  • Remainder section unrelated work

The challenge is designing the entry and exit code so that the critical sections never overlap.

What a correct solution must provide

A valid solution satisfies three properties at once. Mutual exclusion means at most one thread is inside the critical section. Progress means if no thread is inside, the choice of who enters next cannot be postponed forever. Bounded waiting means a thread waiting to enter will get its turn within a finite number of other entries.

Key idea

The critical section problem asks for entry and exit code that delivers mutual exclusion, progress, and bounded waiting together.

Check yourself

Answer to earn rating on the learn ladder.

1. Which three properties must a correct critical section solution provide?

2. What goes wrong if two threads run their critical sections simultaneously on a shared counter?