std::shared_mutex 和 std::shared_lock 是 reader 还是作者更喜欢?

std::shared_mutex with std::shared_lock is reader or writer preferring?

在reader-写锁的实现中,我们可以使用std::shared_mutexstd::shared_lockstd::lock_guardstd::unique_lock.

问题> 这位新功能作家还是 reader 更喜欢?

根据安德鲁的评论更新

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

从上面的例子可以看出,我无法控制 reader/writer 优先级。

两者都不是(如果实施得当)。相反,通过 公平 技术选择读者和作者成为下一个。这就是这个特性在 API 中既不能设置也不能指定的原因。

This answer 详细说明了这是如何完成的。

实践中:

  • libc++ 总是使用 Howard 提到的互斥锁+条件变量技术,这并不奇怪。
  • libstdc++ 在可用的情况下使用 pthread_rwlock_t,如果不可用,则回退到 Howard 提到的算法。因此,如果 pthread_rwlock_t 可用,则使用的算法取决于 pthreads 实现。我相信 glibc 默认更喜欢阅读器。
  • MSVC 使用 Windows SRWLOCK,其 documentation 表示

    There is no guarantee about the order in which threads that request ownership will be granted ownership; SRW locks are neither fair nor FIFO.