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

