liveBook · Manning

Shared_mutex

As explained in C++ Concurrency in Action, Second Edition

A C++ standard library mutex type that supports either exclusive ownership by one thread or shared ownership by multiple threads.

A reader-writer mutex allows one thread exclusive access or multiple threads shared access. Use exclusive locks for updates and shared locks for reads that do not modify the data. An exclusive lock waits until all shared locks have been released. section 3.3.2

For a shared data structure, pair std::shared_mutex with std::shared_lock for reads and std::lock_guard or std::unique_lock for updates. Shared locking adds complexity and is not guaranteed to improve performance; measure on the target system. section 3.3.2

Listing 3.13. Protecting a data structure with std::shared_mutex
#include <map>
#include <string>
#include <mutex>
#include <shared_mutex>
class dns_entry;
class dns_cache
{
    std::map<std::string,dns_entry> entries;
    mutable std::shared_mutex entry_mutex;
public:
    dns_entry find_entry(std::string const& domain) const
    {
        std::shared_lock<std::shared_mutex> lk(entry_mutex);         #1
        std::map<std::string,dns_entry>::const_iterator const it=
            entries.find(domain);
        return (it==entries.end())?dns_entry():it->second;
    }
    void update_or_add_entry(std::string const& domain,
                             dns_entry const& dns_details)
    {
        std::lock_guard<std::shared_mutex> lk(entry_mutex);          #2
        entries[domain]=dns_details;
    }
};


!@%STYLE%@!
{"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":12,\"ch\":69},{\"line\":12,\"ch\":71}],[{\"line\":20,\"ch\":69},{\"line\":20,\"ch\":71}]]"}
!@%STYLE%@!

A DNS cache uses shared access to find entries and exclusive access to add or update them. section 3.3.2

std::shared_mutex is available in C++17; C++14 provides std::shared_timed_mutex, while C++11 provides neither. The timed variant supports additional operations, so std::shared_mutex may be faster on some platforms when those operations are unnecessary. section 3.3.2

How C++ Concurrency in Action, Second Edition covers it

How deep it goes
Explains shared and exclusive lock usage with RAII types, and warns that performance depends on workload and processor count.
Examples
Uses a DNS cache map with shared lookup locks and an exclusive update lock.
What you can do after
Apply shared and exclusive locks to protect read-heavy data structures, then profile performance on the target system.
How it connects
Connects std::shared_mutex to reader-writer mutexes, std::shared_lock, std::unique_lock, std::lock_guard, and std::mutex.

Also explained in

Compare how 2 books explain shared_mutex →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of C++ Concurrency in Action, Second Edition. The section links point to the parts of the book it draws on.