A critical region is the part of a thread that accesses a shared resource. Concurrent threads must coordinate entry to prevent conflicting reads or writes. A mutex guards the region: one thread locks it, performs the protected work, then unlocks it; other threads block while it remains locked. section 16.2 section 16.5
Protecting a critical region follows a small, practical sequence:
- Identify the shared resource and the statements in each thread that access it. section 16.2
- Use the same mutex to guard every critical region associated with that resource. section 16.2
- Lock before entering, keep the protected operation inside the region, and unlock before leaving; failing to unlock can cause deadlock. section 16.5 section 16.2.1
Protecting concurrent output
Three threads print different strings one character at a time. Without protection, their critical regions overlap and produce intermixed, unpredictable output. Locking print_mutex around the character-printing loop allows only one thread at a time to access cout; blocked threads continue after the mutex is unlocked. The order of complete strings can still vary between runs. section 16.2.1
Critical regions can use different lock modes for different access patterns. In a reader–writer design, a unique lock allows one technician to modify a meter while shared locks allow multiple loggers to read it, but readers and writers exclude one another. A producer–consumer queue adds condition variables so threads wait while the queue is full or empty, recheck the condition after notification, and then enter the protected region. section 16.2.2 section 16.3 section 16.3.1
Figure 16.3 Mutex guarding a critical region. It only allows one thread at a time to be in its critical region.
Use the mutex diagram to see how locking limits a critical region to one thread at a time. section 16.2








