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

rub*_*nvb 5 c++ mutex locking c++11 c++14

我想std::mutex在我的班级中使用 a ,并注意到它不可复制。我在我图书馆的底层,所以有这种行为似乎是一个糟糕的主意。

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

Gal*_*lik 9

C++14您可以使用std ::shared_lockstd::unique_lock来实现读/写锁定:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

注意:如果有C++17,则可以使用std::shared_mutexfor mutex_type