Is there a `shared_lock_guard` and if not, what would it look like?

后端 未结 2 989
耶瑟儿~
耶瑟儿~ 2020-12-06 20:03

I wanted to use a std::mutex in my class, and noticed that it isn\'t copyable. I\'m at the bottom level of my library here, so it seems like a terrible idea to

相关标签:
2条回答
  • 2020-12-06 20:39

    It’s not part of C++ standard yet, but you can find implementation example in boost.

    template<typename SharedMutex>
    class shared_lock_guard
    {
    private:
        SharedMutex& m;
    
    public:
        typedef SharedMutex mutex_type;
        explicit shared_lock_guard(SharedMutex& m_):
            m(m_)
        {
            m.lock_shared();
        }
        shared_lock_guard(SharedMutex& m_,adopt_lock_t):
            m(m_)
        {}
        ~shared_lock_guard()
        {
            m.unlock_shared();
        }
    };
    

    It requires mutex class conforming to SharedMutex concept though; std::shared_mutex is part of proposed C++17 standard and boost had one already for some time: boost::shared_mutex.

    0 讨论(0)
  • With C++14 You can use a std::shared_lock and a std::unique_lock to implement read/write locking:

    class lockable
    {
    public:
        using mutex_type = std::shared_timed_mutex;
        using read_lock  = std::shared_lock<mutex_type>;
        using write_lock = std::unique_lock<mutex_type>;
    
    private:
        mutable mutex_type mtx;
    
        int data = 0;
    
    public:
    
        // returns a scoped lock that allows multiple
        // readers but excludes writers
        read_lock lock_for_reading() { return read_lock(mtx); }
    
        // returns a scoped lock that allows only
        // one writer and no one else
        write_lock lock_for_writing() { return write_lock(mtx); }
    
        int read_data() const { return data; }
        void write_data(int data) { this->data = data; }
    };
    
    int main()
    {
        lockable obj;
    
        {
            // reading here
            auto lock = obj.lock_for_reading(); // scoped lock
            std::cout << obj.read_data() << '\n';
        }
    
        {
            // writing here
            auto lock = obj.lock_for_writing(); // scoped lock
            obj.write_data(7);
        }
    }
    

    Note: If you have C++17, then you can use std::shared_mutex for mutex_type.

    0 讨论(0)
提交回复
热议问题