Search⌘ K

Types of Locks: std::shared_lock

Explore how to use std::shared_lock with std::shared_timed_mutex to implement reader-writer locks in C++. Understand the concept of allowing concurrent read access while maintaining exclusive write access, illustrated with a telephone book example. Learn about potential data races and how to avoid undefined behavior when multiple threads access shared data.

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.

...