Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
207 views
in Technique[技术] by (71.8m points)

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

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 have this behaviour.

I used std::lock_guard on the std::mutex, but there doesn't seem to be a shared_lock_guard, which would be preferable to provide write-locks-exclusively behaviour. Is this an oversight or trivial to implement myself?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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() << '
';
    }

    {
        // 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...