Concurrency FundamentalsRace Conditions & Critical SectionsEasy⏱️ ~2 min

Understanding Critical Sections

Definition
A critical section is code that accesses shared resources and must not be executed by more than one thread at a time.

Think Of It Like A Bathroom

A critical section is like a single-occupancy bathroom. One person goes in, locks the door, does their business, and unlocks when done. While locked, others must wait. The lock ensures privacy and prevents awkward collisions.

Critical Section Pattern
LOCKCRITICALSECTIONUNLOCKAcquireOnly 1 threadReleaseOther threads wait here until lock is released

The Four Requirements

Mutual exclusion: Only one thread in the critical section at a time. This is the fundamental requirement.

Progress: If no thread is in the critical section and some want to enter, one must be allowed in. No indefinite postponement.

Bounded waiting: A thread cannot wait forever. There must be a limit on how many times others can enter before you.

No assumptions: The solution must not depend on CPU speed or number of processors.

Keep It Short

Critical sections should be as small as possible. Long critical sections block other threads, reducing parallelism. Only protect what absolutely needs protection.

Rule of Thumb: Enter late, leave early. Acquire the lock just before you need it, release it immediately after.
💡 Key Takeaways
A critical section is code that accesses shared resources and needs protection from concurrent execution.
Entry section acquires a lock, critical section executes, exit section releases the lock. This pattern ensures mutual exclusion.
Mutual exclusion means only one thread executes the critical section at a time. This prevents race conditions.
Progress means the decision of who enters next cannot be delayed by threads not wanting to enter.
Bounded waiting guarantees no thread waits forever. Without it, some threads could starve while others monopolize access.
📌 Examples
1Reading and updating an account balance: lock(); balance = balance - amount; unlock(); The entire operation must be atomic.
2Adding to a linked list: lock(); node.next = head; head = node; unlock(); Both pointer updates must complete together.
← Back to Race Conditions & Critical Sections Overview