/ THE IDEA
The protected stretch is called a critical section. For the ticket example it includes reading availability, checking that a ticket remains, and recording the sale. One worker acquires the lock, completes those steps, then releases it. The next worker sees the updated state. Correct lock operations also establish the memory-ordering rules needed for later owners to observe earlier protected changes. This is more than a courtesy sign. But every relevant access must follow the agreed rule: an uncooperative worker can still read or change the data without taking the lock.
THE FORMAL IDEA
acquire M → check and update shared state → release M
| M names the same mutex for every participant. The arrows specify required order; there is no physical unit. | | “Available” below is a ticket count. “Sold” is the count of successful bookings. The lock protects their relationship, not only one storage location. |
|
RUN THE TINY EXAMPLE
Change one thing. Predict what happens.
Start: available = 1; sold = 0. A acquires M. A checks 1, changes available to 0 and sold to 1, then releases M. B acquires M, sees 0, and refuses a sale. Result: one booking. Change only starting availability to 2: A leaves 1; B then leaves 0. Result: two bookings.
|
The second worker is allowed to run, but its decision uses the state left by the first. The outcome follows the starting stock rather than the timing of overlapping reads. Both updates remain inside the same protected section.
/ SO WHAT?
Keep the protected work focused. Waiting for a slow network response while holding a widely used lock can leave many unrelated workers idle. Moving work outside the lock is useful only if the shared facts cannot become stale between the check and the update; shortening a section carelessly can reintroduce the original race.
ONE CAVEAT |
| A mutex does not protect code that ignores it, and one lock does not automatically coordinate changes protected by another. Process boundaries, language rules and failures require suitable designs beyond this toy sequence. |
KEEP THIS
Lock the whole shared decision, and make every competing access obey the same lock, so the next worker starts from the previous worker’s completed state.
|
NEXT: Why a larger flow can behave less smoothly
|