本文介绍了带有std :: shared_lock的std :: shared_mutex是读者还是作家更喜欢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在实现读写器锁时,我们可以使用 std :: shared_mutex std :: shared_lock std :: lock_guard std :: unique_lock

In implementation of reader-writer lock, we can make use of the std::shared_mutex with std::shared_lock and std::lock_guard or std::unique_lock.

问题>是这个新功能的作家还是读者偏爱?

Question> Is this new feature writer or reader preferring?

根据安德鲁的评论进行更新

Update based on Andrew's comment

  // 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_++;
  }

如上例所示,我无法控制阅读器/

As you can see from above example, I have no control on the reader/writer priority.

推荐答案

两者都不是(如果实施正确)。而是通过 fair 技术选择读者和作家作为下一个。这就是无法在API中设置此特征,也未指定该特征的原因。

It is neither (if implemented properly). Instead readers and writers are chosen to be next by a fair technique. And that is the reason that this characteristic is neither settable in the API, nor specified.

详细说明了如何实现。

This answer details how that is accomplished.

这篇关于带有std :: shared_lock的std :: shared_mutex是读者还是作家更喜欢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 02:47