C ++两个锁比一个锁好

c++ two locks better than one?

本文关键字:一个 两个      更新时间:2023-10-16

我有一个资源(向量,列表等),我正在尝试为多个编写器/读者提供访问权限。

我不确定如何做到这一点以获得最佳性能,即,如果数据结构被锁定,则读取器的锁定量最小。使用两个锁会更好吗,一个称为readmutex,另一个称为writemutex?

所以例如:

struct Foo {
    mutex writemutex_;
    mutex readmutex_;
    vector<string> data_;
    void write(string data)
    {
        lock_guard<mutex> locker(writemutex_);
        data_.emplace_back(move(data));
    }
    string get(int index) const {
        // I don't need to lock for read, but what if the data is being written?
        // and so should I lock lockmutex_? If so, then readmutex_ is unnecessary?
        // is there some cleaver way that I can avoid readers from being blocked?
        return data_[index];
    }
};

我可以在此处使用哪些其他同步技术?

你需要读取器-写入器锁定。但是您应该考虑到,在某些场景中,rw锁可能比独占锁慢

有很多实现,例如在 boost 中。WinAPI也有一个(自Vista或Server 2008以来)

您可以使用

boost中可用的shared_mutex,并且将成为C++14的一部分。

struct Foo 
{
    using mutex = boost::shared_mutex;
    using write_lock = boost::unique_lock<mutex>;
    using read_lock = boost::shared_lock<mutex>;
    mutable mutex mutex_;
    vector<string> data_;
    void write(string data)
    {
        write_lock lock{ mutex_ };
        data_.emplace_back(move(data));
    }
    string get(int index) const 
    {
        read_lock lock{ mutex_ };
        return data_[index];
    }
};

回答您的主要问题:不,使用两个锁并不好。这实际上是不正确的。您需要写锁定来防止竞争,并且在持有写锁定时,不需要任何额外的读锁定。

其他答案确实有正确的替代方案(shared_mutex,它实现了读写锁),但没有解释为什么需要它。

相关文章: