liveBook · Manning

Locking

As explained in Object-Oriented Software Design in C++

Mutual exclusion is a synchronization property that restricts access to a protected resource so that only one thread can enter the critical operation at a time.

Mutual exclusion protects a shared resource by allowing only one thread at a time to enter the critical region that accesses it. Without this protection, simultaneous updates can create race conditions and unpredictable results. section 16.1 section 16.2

A mutex enforces the rule. A thread locks the mutex before entering its critical region and unlocks it afterward; a thread that finds the mutex locked blocks until it can try again. Every critical region for the same shared resource uses that mutex. section 16.2 section 16.5

Protecting a shared print stream

Three threads print different strings one character at a time. With no mutex, their output becomes intermixed and may differ on every run. Adding a shared print mutex around the character-printing loop makes each protected operation run exclusively. The runtime system still determines which waiting thread acquires the unlocked mutex, so execution order remains unpredictable. Forgetting to unlock the mutex before leaving the critical region can cause deadlock. section 16.2.1 section 16.5

Figure 16.2 The critical regions of threads A and B modify the same shared resource, variable X. A mutex object guards the critical regions. A thread that successfully locks the mutex can enter its critical region. Attempting to lock a mutex that’s already locked causes the thread to block. The thread that’s exiting its critical region must unlock the mutex to allow another thread to lock it.

Visualizes two threads competing for one mutex while modifying the same shared variable: one enters, while the other blocks until unlock. section 16.2

How Object-Oriented Software Design in C++ covers it

How deep it goes
Explains critical regions, mutex lock-block-unlock behavior, scheduling variability, and deadlock risk, while deferring condition-variable synchronization.
Examples
Uses three C++ threads writing different strings character by character to a shared print stream.
What it assumes
Assumes basic threads and shared resources, then builds critical regions and race conditions through a printing example.
What you can do after
Apply it via C++ mutexes to guard critical regions and diagnose interleaved output caused by unprotected shared resources.
How it connects
Connects mutexes with critical sections, race conditions, condition variables, reader-writer problems, and producer-consumer problems.

Also explained in

Compare how 18 books explain locking →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Object-Oriented Software Design in C++. The section links point to the parts of the book it draws on.