std::unique_lock, std::shared_lock, std::lock_guard

suggest change

Used for the RAII style acquiring of try locks, timed try locks and recursive locks.

std::unique_lock allows for exclusive ownership of mutexes.

std::shared_lock allows for shared ownership of mutexes. Several threads can hold std::shared_locks on a std::shared_mutex. Available from C++ 14.

std::lock_guard is a lightweight alternative to std::unique_lock and std::shared_lock.

#include <unordered_map>
#include <mutex>
#include <shared_mutex>
#include <thread>
#include <string>
#include <iostream>

class PhoneBook {
public:
    std::string getPhoneNo( const std::string & name )
    {
        std::shared_lock<std::shared_timed_mutex> l(_protect);
        auto it =  _phonebook.find( name );
        if ( it != _phonebook.end() )
            return (*it).second;
        return "";
    }
    void addPhoneNo ( const std::string & name, const std::string & phone )
    {
        std::unique_lock<std::shared_timed_mutex> l(_protect);
        _phonebook[name] = phone;
    }
    
    std::shared_timed_mutex _protect;
    std::unordered_map<std::string,std::string>  _phonebook;
};

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents