是否有 `shared_lock_guard`,如果没有,它会是什么样子?

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

我想在我的 class 中使用 std::mutex,但发现它不可复制。我在我的图书馆的底层,所以有这种行为似乎是个糟糕的主意。

我在 std::mutex 上使用了 std::lock_guard,但似乎没有 shared_lock_guard,它更适合提供独占写锁行为。这是我自己实施的疏忽还是微不足道的?

C++14可以用std::shared_lock and a std::unique_lock实现read/write锁定:

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.

它还不是 C++ 标准的一部分,但你可以在 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();
    }
};

它需要符合 SharedMutex 概念的互斥 class; std::shared_mutex is part of proposed C++17 standard and boost had one already for some time: boost::shared_mutex.