尝试 std::lock[_unique] 和 std::shared_mutex 的线程是否会被调用 std::lock_shared 的线程饿死?

Can thread trying to std::lock[_unique] an std::shared_mutex be starved by threads calling std::lock_shared?

关于std::shared_mutexunique_lock获得的问题。

假设有 3 个线程:

尝试 lock[_unique]() 的作者有可能饿死吗?例如:在任何时候至少有一个 reader 拥有一个 std::shared_lock,并且 lock[_unique]() 永远不会成功。

或多或少:lock[_unique]() std::shared_mutex 会阻止任何进一步 lock_shared() 它的尝试吗?


(很确定 boost::upgrade_lock 可以在这里工作,但我想知道 std::shared_mutex 上的裸 std::unique_lock 是否有任何保证)

More or less: would lock[_unique]() on a std::shared_mutex block any attempts to further lock_shared() it?

标准没有具体说明是否应该发生,它只是说:

Effects: Blocks the calling thread until shared ownership of the mutex can be obtained for the calling thread.

所以是否让后来的读者在待处理的作者后面等待,这取决于实现。

如果实现想要防止写入器饥饿,那么它可能需要在线程尝试获取唯一锁时设置一个 "writer waiting" 标志,以便稍后获取共享锁的尝试将被阻止,等待在独特的储物柜后面。在 N2406 参考实现中,这是 state 成员中的 write_entered_ 位。