gpt4 book ai didi

c++ - std::shared_mutex 是否有利于作者而不是读者?

转载 作者:可可西里 更新时间:2023-11-01 18:39:21 33 4
gpt4 key购买 nike

从 C++17(C++14) 开始,我们有了 std::shared_(timed_)mutex 类。很长一段时间以来,Qt 都有一个类似的类 QReadWriteLock。 QReadWriteLock 的 documentation说:

To ensure that writers aren't blocked forever by readers, readers attempting to obtain a lock will not succeed if there is a blocked writer waiting for access, even if the lock is currently only accessed by other readers. Also, if the lock is accessed by a writer and another writer comes in, that writer will have priority over any readers that might also be waiting.

因为这当然是一个合理的属性(property),我想知道是否 std::shared_mutexstd::shared_timed_mutex以类似的方式行事?

最佳答案

官方 C++ 标准未指定 std::shared_mutex 策略。可以在原始 N2406 提案中找到解释( http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2406.html#shared_mutex_imp ) shared_mutex 引用实现部分:

A secondary motivation is to explain the lack of reader-writer priority policies in shared_mutex. This is due to an algorithm credited to Alexander Terekhov which lets the OS decide which thread is the next to get the lock without caring whether a unique lock or shared lock is being sought. This results in a complete lack of reader or writer starvation. It is simply fair.

与 QReadWriteLock 实现(即优先写入)相比:

To ensure that writers aren't blocked forever by readers, readers attempting to obtain a lock will not succeed if there is a blocked writer waiting for access, even if the lock is currently only accessed by other readers.

提案的 shared_mutex 也是如此,以确保如果新读者不断涌入,编写者不会永远等待。

Also, if the lock is accessed by a writer and another writer comes in, that writer will have priority over any readers that might also be waiting.

提案的 shared_mutex 不是这样,读者和作者在这种情况下具有同等的优先级。

但不幸的是,最终的 C++ 标准文档不包含此引用实现。请注意,尽管 GCC 包含基于 N2406 引用实现的 std::shared_mutex 实现,但在 Linux 上它默认不使用,它使用来自 POSIX 线程库的 pthread_rwlock_t (由 c++config.h 中的 _GLIBCXX_USE_PTHREAD_RWLOCK_T 选项控制)。 pthread_rwlock_t 可以优先读取或写入,具体取决于系统设置和应用的 pthread 属性。详情见相关问题:How to prevent writer starvation in a read write lock in pthreads

关于c++ - std::shared_mutex 是否有利于作者而不是读者?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57706952/

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