Process Synchronization & the Critical-Section Problem

the critical section

Picture a small bathroom shared by a whole office. Only one person can use it at a time, so there is a lock on the door. The bathroom itself is the dangerous shared resource; the act of being inside it is the part of your day that must not overlap with anyone else's. A critical section is the software version of that bathroom: it is the specific stretch of code in which a thread reads and modifies shared data, so that two threads running it at the same time could corrupt that data.

Concretely, a thread's code is usually divided into four conceptual parts: an entry section (where it asks permission to enter), the critical section (where it actually touches the shared data), an exit section (where it gives up its permission), and the remainder section (everything else, which is safe to run concurrently). The whole craft of synchronization is to build the entry and exit sections so that no two threads are ever in their critical sections at the same time. The critical section should be as short as possible — only the few lines that genuinely touch shared state — because while one thread is inside, others that need it must wait, and a long critical section throttles concurrency.

A common misconception is that a critical section is a property of the data or of one function. It is really a property of every code path that touches the shared data. If even one thread reads or writes the shared variable without going through the entry section, the protection is broken — that one careless access can corrupt everything, no matter how carefully every other thread behaves. Identifying every critical section that touches a given piece of shared state is the first, and easiest-to-get-wrong, step in writing correct concurrent code.

In a bank, transfer(a, b, amt) reads both balances, subtracts from a, and adds to b. Those few lines are the critical section: if two transfers touching account a interleave, money can be created or destroyed. The deposit/withdraw forms, status logging, and printing receipts are remainder code and need no protection.

Entry -> critical section -> exit -> remainder; keep the critical section tiny.

A critical section protects nothing unless every path that touches the shared data goes through the same entry/exit discipline. One unsynchronized access elsewhere defeats it entirely.

Also called
critical region臨界區段臨界區域