C++17 introduces the std::shared_mutex
type. I have been looking at the documentation over on CppReference with a particular interest for cases that produce undefined behavior.
While reading through both unlock methods (one for releasing exclusive ownership, one for releasing shared ownership), I've noticed the documentation is a little vague on one occasion.
For std::shared_mutex::unlock_shared
, the documentation states (emphasis mine):
The mutex must be locked by the current thread of execution in shared mode, otherwise, the behavior is undefined.
It is clearly indicated that a call to unlock_shared
must be preceded by a call to lock_shared
as that is the only way to lock the mutex in shared mode.
For std::shared_mutex::unlock
, the documentation states:
The mutex must be locked by the current thread of execution, otherwise, the behavior is undefined.
There is no mention of the level of access the current thread of execution must hold before calling unlock
. This made me wonder if it is also capable of releasing shared ownership as well as exclusive ownership.
My question: is it undefined behavior to release shared ownership of a std::shared_mutex
with a call to unlock
instead of unlock_shared
?
If possible, I'd like a quote from the C++ standard that explicitly confirms or denies undefined behavior in the aforementioned scenario.
Per [thread.mutex.requirements.mutex] we have
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.
So, as long as the thread owns the mutex ,whether it is in shared mode or not, unlock
will release the threads ownership of the mutex.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With