c++ - 在共享模式下锁定的 std::shared_mutex 上调用解锁

标签 c++ multithreading language-lawyer mutex

C++17 引入了 std::shared_mutex 类型。我一直在查看 CppReference 上的文档对产生未定义行为的情况特别感兴趣。

在通读两种解锁方法(一种用于释放独占所有权,一种用于释放共享所有权)时,我注意到文档有一次有点含糊。

对于 std::shared_mutex::unlock_shared ,文档说明(强调我的):

The mutex must be locked by the current thread of execution in shared mode, otherwise, the behavior is undefined.

它清楚地表明调用unlock_shared必须先调用 lock_shared因为这是在共享模式下锁定互斥锁的唯一方法。

对于 std::shared_mutex::unlock ,文档指出:

The mutex must be locked by the current thread of execution, otherwise, the behavior is undefined.

没有提及当前执行线程在调用 unlock 之前必须持有的访问级别.这让我想知道它是否也能够释放共享所有权和独占所有权。

我的问题:释放 std::shared_mutex 的共享所有权是未定义的行为吗?调用 unlock而不是 unlock_shared

如果可能的话,我想要引用 C++ 标准中明确确认或否认上述场景中未定义行为的内容。

最佳答案

根据 [thread.mutex.requirements.mutex]我们有

The expression m.unlock() shall be well-formed and have the following semantics:

Requires: The calling thread shall own the mutex.

Effects: Releases the calling thread's ownership of the mutex.

Return type: void.

Synchronization: This operation synchronizes with subsequent lock operations that obtain ownership on the same object.

Throws: Nothing.

因此,只要线程拥有互斥量,无论是否处于共享模式,unlock 都会释放线程对互斥量的所有权。

关于c++ - 在共享模式下锁定的 std::shared_mutex 上调用解锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44652353/

相关文章:

c++ - 如何使用 printf 打印 "%"字符

c++ - 有没有关闭计算机的C++函数?

c# - NHibernate 锁定数据库表以避免插入 "duplicates"

c++ - 是否将 std::time 与 std::srand 有效代码一起使用?

c++ - `std::basic_string::operator[]` 能否返回一个 "distant"保护页 nul 终止符?

c++ - 为什么未诊断出在 constexpr 上下文中使用保留的标识符名称?

c++ - 为什么 `const int& k = i;++i; ` 可能?

c++ - 返回 std::stringstream - 编译失败

android - 使用协程进行多次循环调用

c# - 从多个线程异步写入文件c#