在读写锁的实现中,我们可以使用 std::shared_mutex
和 std::shared_lock
和 std::lock_guard
或 std::unique_lock
。
问题 > 这个新功能作者或读者更喜欢吗?
根据安德鲁的评论更新
Reference :
// Multiple threads/readers can read the counter's value at the same time.
unsigned int get() const {
std::shared_lock<std::shared_mutex> lock(mutex_);
return value_;
}
// Only one thread/writer can increment/write the counter's value.
void increment() {
std::unique_lock<std::shared_mutex> lock(mutex_);
value_++;
}
从上面的示例中可以看出,我无法控制读取器/写入器的优先级。
最佳答案
两者都不是(如果实现得当)。相反,读者和作者是通过一种公平的技术被选为下一个的。这就是这个特性在 API 中既不可设置也不指定的原因。
This answer 详细说明了如何实现。
关于c++ - 带有 std::shared_lock 的 std::shared_mutex 是读者还是作者更喜欢?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43309333/