difference between std::mutex and std::shared_mutex

后端 未结 3 1970
半阙折子戏
半阙折子戏 2021-02-07 08:27

I came across an std::shared_mutex in C++17. what exactly is std::shared_mutex and how it is different from std::mutex?

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-07 09:19

    std::shared_mutex can be useful especially in cases where data structure (like DNS cache) gets rarely updated. Using a std::mutex to protect the data structure could be overly pessimistic, because it eliminates the possible concurrency in reading the data structure when it isn’t undergoing modification. Multiple threads can have a shared lock on the same std::shared_mutex at the same time.

    One such example from Anthony Williams book:

    class dns_cache
    {
        std::map entries;
        mutable boost::shared_mutex entry_mutex;
    
    public:
    
        dns_entry find_entry(std::string const& domain) const
        {
            boost::shared_lock lk(entry_mutex);
            std::map::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 lk(entry_mutex);
            entries[domain] = dns_details;
        }
    };
    

    Here, function find_entry basically does the Read operation, whereas update_or_add_entry performs the Write operation.

    So, it can said that std::shared_mutex is a typical reader-writer mutex, because it allows for two different kinds of usage: exclusive access by a single “writer” thread or shared, concurrent access by multiple “reader” threads.

提交回复
热议问题