Course contentsShow
← Computer Science
Lesson 2556 of 2,87257. Concurrency FundamentalsFree lesson

Critical Sections

Identify critical sections of code that access shared mutable state and require protection.

Critical Sections

You'll learn how to pinpoint the dangerous zones in your code where shared data gets modified concurrently.

What Are Critical Sections?

A critical section is any portion of code that accesses shared mutable state (data that multiple threads can modify). These sections are "critical" because if two or more threads execute them simultaneously without coordination, race conditions occur—leading to corrupted data, inconsistent state, or unpredictable behavior.

Think of a critical section like a narrow bridge that only one car should cross at a time. If multiple cars try to cross simultaneously, they'll crash. The bridge itself isn't the problem—the simultaneous access is.

Identifying Critical Sections

Look for code that performs read-modify-write operations on shared data:

// Critical section: multiple threads reading AND writing balance
balance = balance + amount

If thread A reads balance = 100, and thread B simultaneously reads balance = 100, then both add 50, both write back 150—you've lost one deposit! The final balance should be 200.

Not every shared data access is critical:

  • Reading immutable data: Safe, no critical section
  • Reading without writing: Usually safe (with caveats)
  • Local variables: Never shared, never critical

The Protection Requirement

Once you've identified a critical section, you must protect it to ensure only one thread executes it at a time. This mutual exclusion prevents race conditions by serializing access to the shared state.

The key is finding the minimal critical section—protect only what needs protecting. Locking too much code reduces concurrency benefits; locking too little allows race conditions.

Key Takeaway: Critical sections are the read-modify-write code paths accessing shared mutable state; identifying them correctly is essential before applying any synchronization mechanism to prevent race conditions.