Types of Locks: std::shared_lock

This lesson gives an overview of the std::shared_lock which is a type of lock used in C++.

A std::shared_lock has the same interface as a std::unique_lock but behaves differently when used with a std::shared_timed_mutex. Many threads can share one std::shared_timed_mutex and, therefore, implement a reader-writer lock. The idea of reader-writer locks is straightforward and extremely useful. An arbitrary number of threads executing read operations can access the critical region at the same time, but only one thread is allowed to write.

Reader-writer locks do not solve the fundamental problem - threads competing for access to a critical region, but they do help to minimize the bottleneck.

Telephone book example for reader-writer locks

A telephone book is a typical example using a reader-writer lock. Usually, a lot of people want to look up a telephone number, but only a few want to change them. Let’s look at an example.

Get hands-on with 1400+ tech skills courses.