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

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

我在std :: mutex上使用了std :: lock_guard,但似乎没有shared_lock_guard,这对于提供write-locks-exclusive行为更为可取.这是实施自己的疏忽或微不足道的事情吗?

解决方法:

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

注意:如果你有C 17,那么你可以使用std :: shared_mutex作为mutex_type.

上一篇:c – std :: lock_guard或std :: scoped_lock?


下一篇:linux – 如何在使用锁文件时避免竞争条件以避免脚本的两个实例同时运行?