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/