Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call unlock on std::shared_mutex that is locked in shared mode

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.

like image 448
Maarten Bamelis Avatar asked Jun 20 '17 11:06

Maarten Bamelis


1 Answers

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.

like image 94
NathanOliver Avatar answered Oct 24 '22 17:10

NathanOliver