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

标签 c++ multithreading

从 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/

相关文章:

c++ - CPP + 正则表达式来验证 URL

拥有对象的 C++ shared_ptr 调用析构函数

python - 两个进程之间的IPC示例,opencv(cv::Mat对象)c++作为服务器,python作为客户端

c++ - 如何确保多线程 C++ 程序由多核服务器上的所有内核运行?

java - 有没有更优雅的方式来启动基于列表的线程?

c++ - 使用多线程时程序变慢

c++ - 带有类的 typedef 函数声明 - 非静态成员调用?

c++ - 如何更改集合中的对象子成员

c++ - 正确声明指针,分配内存,并将它们作为参数发送 c++

java - 如果对 int 变量的写入和读取是原子的,为什么需要 AtomicInteger?