liveBook · Manning

Shared_lock

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

A C++ standard library lock-management class that provides shared ownership of a mutex for concurrent readers.

shared_lock manages shared ownership of a shared_mutex. Multiple reader threads can hold shared locks simultaneously, while a writer using unique_lock must wait until all readers release the mutex. section 16.2.2

Use shared_lock when a critical region only reads shared state:

  • Pair shared readers with unique_lock writers: readers may coexist, but neither readers nor writers may overlap a writer. section 16.2.2

Meter readers

Three logger threads acquire shared_lock to copy the meter setting and log it. Technician threads acquire unique_lock while changing the setting, preventing readers from observing an active update.

Figure 16.6 Three technicians simultaneously attempt to set the meter’s value; meanwhile, three loggers attempt to read and log the meter’s current setting. Therefore, the meter is the shared resource. Only one technician should be setting the meter at a time, and no logger should read the meter while a technician is setting it. However, unless a technician is setting the meter, multiple loggers can be reading it at the same time.

The technician-and-logger scenario shows why concurrent reads are permitted while writes require exclusive access. section 16.2.2

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

How deep it goes
Explains shared and unique ownership and demonstrates scoped locking, but does not detail implementation internals.
Examples
Demonstrates logger threads reading a shared meter while technician threads update it.
What it assumes
Assumes mutexes, threads, shared resources, and critical regions; distinguishes reader and writer behavior explicitly.
What you can do after
Apply it via C++ shared_mutex to protect read-only critical regions in multithreaded programs.
How it connects
Connects shared_lock with shared_mutex, unique_lock, mutexes, critical regions, and the reader-writer problem.

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.