unique_lock is a C++ lock-management class that gives one thread exclusive ownership of a mutex. The lock protects a critical region and releases the mutex automatically when the lock object leaves scope. section 16.2.2 section 16.3.1
Use unique_lock when a thread must modify shared data or coordinate with a condition variable:
- Keep the protected operation inside its scope; leaving that scope unlocks the mutex. section 16.3.1
- Pass the lock to condition_variable::wait so waiting can suspend the thread and later recheck the condition with the mutex protected. section 16.3.1
- Choose shared_lock instead when multiple threads should read a shared_mutex concurrently without modifying the resource. section 16.2.2
Protecting a shared meter
A technician creates unique_lock<shared_mutex> writing_lock(meter_mutex) before changing the meter setting. While the lock is held, other technicians cannot write and loggers cannot read. The lock’s scope covers the meter update and its timed operation, then releases the mutex automatically. section 16.2.2
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 diagram shows why exclusive locking is needed for writers while allowing simultaneous readers when no writer is active. section 16.2.2

