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++.

An std::shared_lock has the same interface as an std::unique_lock but behaves differently when used with an 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 of 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.