Course contentsShow
← Computer Science
Lesson 1273 of 2,87230. Process SynchronizationFree lesson

Critical Sections Defined

Understanding critical sections as code segments that access shared resources and must not be executed concurrently.

Critical Sections Defined

What you'll learn: You'll understand what critical sections are and why identifying them is essential for preventing race conditions.


What Is a Critical Section?

A critical section is a segment of code that accesses shared resources (like variables, files, or data structures) and must not be executed by multiple threads or processes at the same time.

Think of it like a single-occupancy bathroom. The bathroom is a shared resource. The time someone spends inside using it is their "critical section"—only one person can be in there at a time, or chaos ensues.

Why Critical Sections Matter

From our earlier lessons on race conditions, you learned that when multiple threads interleave while accessing shared data, unpredictable results occur. The root problem? Those threads were executing critical sections simultaneously.

For example, consider this shared counter increment:

1. Load counter value into register
2. Add 1 to register
3. Store register value back to counter

These three steps form a critical section. If two threads execute them at the same time with interleaving, the counter may only increase by 1 instead of 2—a classic race condition.

Identifying Critical Sections

To spot a critical section in your code, ask:

  • Does this code read or write shared data?
  • Could another thread access the same data simultaneously?

If both answers are "yes," you've found a critical section that needs protection.


Key Takeaway: A critical section is any code segment that accesses shared resources and requires exclusive execution to prevent race conditions—only one thread should execute it at a time.