是否有一个"shared_lock_guard",如果没有,它将是什么样? [英] Is there a `shared_lock_guard` and if not, what would it look like?

查看:53
本文介绍了是否有一个"shared_lock_guard",如果没有,它将是什么样?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在课堂上使用std::mutex,并注意到它不可复制.我在我图书馆的最底层,所以拥有这种行为似乎是一个可怕的主意.

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.

我在std::mutex上使用了std::lock_guard,但是似乎没有shared_lock_guard,这对于提供排他性的写锁行为是更可取的.这是对自己实施的疏忽或琐碎?

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?

推荐答案

使用 C++14 ,您可以使用

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

注意:如果您具有 C++17 ,则可以将std::shared_mutex用于mutex_type.

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

这篇关于是否有一个"shared_lock_guard",如果没有,它将是什么样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆