stdunique lock stdshared lock stdlock guard

用于 RAII 样式获取 try 锁,定时 try 锁和递归锁。

std::unique_lock 允许互斥锁的独占所有权。

std::shared_lock 允许互斥锁的共享所有权。几个线程可以在 std::shared_mutex 上保存 std::shared_locks。可从 C++ 14 获得。

std::lock_guardstd::unique_lockstd::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;
};