liveBook · Manning

Unique_lock

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

A C++ standard library lock-management class that provides exclusive ownership of a mutex and releases that ownership automatically when the lock object is destroyed.

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

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

How deep it goes
Explains construction, scope-based unlocking, reader-writer behavior, and condition-variable waiting, without detailing the class implementation.
Examples
Uses technician and logger threads sharing a meter, plus producer and consumer threads sharing a bounded queue.
What it assumes
Assumes mutexes, threads, shared resources, and critical regions while explaining lock scope and waiting behavior directly.
What you can do after
Apply it via C++ mutexes and condition variables to guard critical regions and synchronize access to shared data.
How it connects
Connects unique_lock with mutex, shared_mutex, shared_lock, critical regions, condition variables, and producer-consumer synchronization.

Also explained in

Compare how 2 books explain unique_lock →

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.