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

烂漫一生 提交于 2019-12-18 08:55:28

问题


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

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

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


回答1:


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.




回答2:


In practice:

  • libc++ always uses the mutex+condition variables technique Howard mentioned, not surprisingly.
  • libstdc++ uses pthread_rwlock_t where available, falling back to the algorithm Howard mentioned if it is not. Therefore if pthread_rwlock_t is available, the algorithm used depends on the pthreads implementation. I believe that glibc prefers readers by default.
  • MSVC uses Windows SRWLOCK, whose documentation says

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



来源:https://stackoverflow.com/questions/43309333/stdshared-mutex-with-stdshared-lock-is-reader-or-writer-preferring

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!