gpt4 book ai didi

c++ - std::shared_mutex 和 std::shared_lock 是读者还是作者更喜欢?

转载 作者:太空狗 更新时间:2023-10-29 20:21:34 28 4
gpt4 key购买 nike

在读写锁的实现中,我们可以利用std::shared_mutexstd::shared_lockstd::lock_guardstd::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_++;
}

从上面的例子可以看出,我无法控制读写器的优先级。

最佳答案

实践中:

  • 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.

关于c++ - std::shared_mutex 和 std::shared_lock 是读者还是作者更喜欢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43309333/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com